如何从 C# 中的 DLL 获取类型列表?
我想将 C# 应用程序指向 DLL,并获取该 DLL 中定义的类型列表。 到目前为止,我所看到的表面上看起来很正确,但给出了下面指出的错误。
using System.Reflection;
...
static void Main(string[] args)
{
Assembly SampleAssembly;
SampleAssembly = Assembly.LoadFrom("C:\\MyAssembly.dll"); //error happens here
foreach (Type tp in SampleAssembly.GetTypes())
{
Console.WriteLine(tp.Name);
}
}
/*
This will give me:
Unable to load one or more of the requested types.
Retrieve the LoaderExceptions property for more information.
I wish it would give me something like this:
MyClass1
MyClass2
MyClass3
*/
I'd like to point a C# application at a DLL and get a list of the types defined in that DLL.
What I have so far looks right on the surface, but is giving the error indicated below.
using System.Reflection;
...
static void Main(string[] args)
{
Assembly SampleAssembly;
SampleAssembly = Assembly.LoadFrom("C:\\MyAssembly.dll"); //error happens here
foreach (Type tp in SampleAssembly.GetTypes())
{
Console.WriteLine(tp.Name);
}
}
/*
This will give me:
Unable to load one or more of the requested types.
Retrieve the LoaderExceptions property for more information.
I wish it would give me something like this:
MyClass1
MyClass2
MyClass3
*/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 ReflectionOnlyLoad 而不是直接加载,以防止运行时尝试运行目标程序集中的任何代码
Use ReflectionOnlyLoad instead of a straight load to prevent the runtime from attempting to run any code in the target assembly
抛出 ReflectionTypeLoadException 是因为您的一种类型在静态初始化期间抛出异常。如果方法/属性/字段签名依赖于不可用的类型,则可能会发生这种情况。我建议您捕获该异常并按照建议检查异常的 LoaderExceptions 属性的内容。
The ReflectionTypeLoadException is being thrown because one of your types is throwing an exception during static initialization. This can happen if the method/property/field signatures depend on a Type that is not available. I recommend you catch for that exception and inspect the contents of the exception's LoaderExceptions property as suggested.