如何从C#中的DLL获取类型列表?

时间:2010-08-19 21:40:13

标签: c# reflection assemblies

我想在DLL上指出一个C#应用程序,并获取该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
*/

2 个答案:

答案 0 :(得分:5)

使用ReflectionOnlyLoad而不是直接加载来阻止运行时尝试运行目标程序集中的任何代码

答案 1 :(得分:2)

抛出ReflectionTypeLoadException,因为您的某个类型在静态初始化期间抛出异常。如果方法/属性/字段签名依赖于不可用的类型,则会发生这种情况。我建议您捕获该异常并按照建议检查异常的LoaderExceptions属性的内容。