在对象列表中加载未引用程序集的类型
本文关键字:引用 程序集 类型 加载 对象 列表 | 更新日期: 2023-09-27 18:35:08
我想从未引用的程序集中获取类型。我用这个答案来解决我的问题。
现在的问题是,我正在加载包含另一个程序集中的另一种类型的类型 ObjectList
。我是这样做的:
Assembly assembly = Assembly.LoadFrom ("@c:'myAssemblies'myAssembly.Data.DomainObjects.dll");
Type myType = assembly.GetType ("myAssembly.Data.DomainObjects.ObjectList`1[[myAssembly.otherNamespace.myClass, myAssembly.otherNamespace, Version=1.13.73.1082, Culture=neutral, PublicKeyToken=fee00910d6e5f53b]]");
带有otherNamespace
的程序集也不会被引用,因此 GetType
方法返回 null
。我现在的问题是:
是否可以获取包含另一种类型的未引用程序集的对象列表的类型?或者:如何在ObjectList
中加载类型的程序集?
好的,这对我来说有点难以测试 - 但我希望我的答案可以转换:
基本上,您需要分两步完成 -
- 解析泛型参数类型(myAssembly.otherNamespace.myClass,在您的情况下)
- 根据泛型参数的类型生成新类型。
下面是一个 Linqpad 脚本:
void Main()
{
//resolve the inner type
var parameterType = Type.GetType("UserQuery+GenericParameter");
//Use the generic type, and generate with the inner parameter type
var genericTypeWithParameter = Type.GetType("UserQuery+Moop`1")
.MakeGenericType(parameterType);
//The resolved type - printed to console
genericTypeWithParameter.Dump();
}
public class Moop <T> { }
public class GenericParameter { }
我对此不是 100% 确定,但是当我尝试这样做时:
public class Moop<T> {}
我做到:
Type.GetType("UserQuery.Moop`1") //returns null
Type.GetType("UserQuery+Moop`1") //returns the correct type
在林克帕德
编辑:"+"表示它只是一个嵌套类型 - 所以,这可能不是正确的答案。
如果程序集 myAssembly.otherNamespace.dll 与可执行文件不在同一目录中或安装在 GAC 中,则公共语言运行库找不到它。因此,myAssembly.otherNamespace.dll 不会加载到 AppDomain 中,并且您无法获取所需的类型。
将 myAssembly.Data.DomainObjects.dll 和 myAssembly.otherNamespace.dll 放到可执行文件所在的同一目录中,或将它们安装到 GAC 中。然后使用 Load(而不是 LoadFrom)来确保将它们加载到同一个 Load Cntext 中。
如果程序集 myAssembly.Data.DomainObjects.dll 中的元数据包含对程序集 myAssembly.otherNamespace.dll 的引用,则在加载前者时应自动加载后者。否则,必须先加载这两个程序集,然后才能获得所需的类型。