如何从一个未引用组件的类型?组件、类型

2023-09-03 04:24:42 作者:薄荷味的回忆

的GetType()返回null 当类型未引用组件存在。例如,当出现以下称为localType(即使使用类的完整的命名空间名)总是空:

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");

我看不出有任何理由Type.GetType不应该能够从一个未引用集检索类型,所以

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

推荐答案

使用 LoadFrom 加载未引用的程序集从它的位置。然后调用 的GetType

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

如果加载程序集是在你从(如C:\ ProjectY \ BIN \发布\ ProjectX.dll)加载程序集的私有路径,可以使用的 加载

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");