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 开发者_Go百科like this:
MyClass1
MyClass2
MyClass3
*/
Use ReflectionOnlyLoad instead of a straight load to prevent the runtime from attempting to run any code in the target assembly
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.
精彩评论