简体   繁体   中英

How can I get a list of types from a DLL in C#?

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
*/

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM