How to get a type from an unreferenced assembly?

霸气de小男生 提交于 2019-12-01 07:09:27

问题


GetType() returns null when the type exists in an unreferenced assembly. For example, when the following is called "localType" is always null (even when using the full namespace name of the class):

Type localType = Type.GetType("NamespaceX.ProjectX.ClassX");

I don't see any reason why Type.GetType shouldn't be able to retrieve a type from an unreferenced assembly, so

How can the type of an unreferenced assembly be retrieved?


回答1:


Use LoadFrom to load the unreferenced assembly from it's location. And then call GetType.

Assembly assembly = Assembly.LoadFrom("c:\ProjectX\bin\release\ProjectX.dll");
Type type = assembly.GetType("NamespaceX.ProjectX.ClassX");

If the assembly to load is in the private path of the assembly you're loading from (like "c:\ProjectY\bin\release\ProjectX.dll"), you can use Load.

Assembly assembly = Assembly.Load("ProjectX.dll");
Type type = assembly.GetType("NamespaceX.ProjectX.ClassX");



回答2:


From the MSDN documentation

If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.

It also indicates null will be returned if the assembly isn't loaded from disk.

One work around you might try is loading the assembly and then using the GetType methods on the assembly directly. Admittedly from the documentation it sounds like it should have thrown an exception if the problem was in loading the assembly.



来源:https://stackoverflow.com/questions/463228/how-to-get-a-type-from-an-unreferenced-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!