Type. GetType () solution to return null when cross-assembly reflection

Source: Internet
Author: User

This situation is often encountered during development. In Assembly A. dll, the type in assembly B. dll needs to be reflected. A running error occurs if you are not careful with it. For example, if Type. GetType ("BNameSpace. ClassName") is used in Assembly A. dll to obtain the Type in assembly B. dll, Null is returned.

For cross-assembly reflection, pay attention to the following two points:

 

1. If typeof is used, the cross-assembly reflection will certainly run normally. It can be said that typeof supports strong types. For example

1 Type supType = typeof (BNameSpace. SubSpace. Class );

If the current Assembly does not add a reference to EnterpriseServerBase. dll, an error is reported during compilation.

 

2. If Type. GetType is used for reflection, the situation is more complicated. This is because Type. GetType is of a non-strong Type. The Type. GetType parameter is a fully qualified name of the string Type. If the target Type indicated by string is not in the current Assembly, Type. GetType will return null at runtime. Solution: First load the target Assembly, and then use the Assembly. GetType method to obtain the type. For example

1 Assembly asmb = Assembly. LoadFrom ("EnterpriseServerBase. dll ");
2 Type supType = asmb. GetType ("EnterpriseServerBase. DataAccess. IDBAccesser ");

 

Note that when Type. when GetType is used, even if you have added the parameter iseserverbase. dll reference, Type. getType ("EnterpriseServerBase. dataAccess. IDBAccesser ") also returns null because of Type. getType only searches for the type in the current dataset!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.