Listing all the classes in a DLL

2019-09-15 16:37发布

问题:

I would like to list all of the classes that are in a DLL without having to load the dependencies. I don't want to execute any functionality, I just want to find out (problematically) what classes are inside of a given DLL. Is that possible? I've tried using the assembly.GetTypes() call, but it fails because of dependencies for executing the DLL. Is there any other way to list all the public classes?

回答1:

I suggest you use the mono Cecil library. This is the basic example:

//Creates an AssemblyDefinition from the "MyLibrary.dll" assembly
AssemblyDefinition myLibrary = AssemblyFactory.GetAssembly ("MyLibrary.dll");

//Gets all types which are declared in the Main Module of "MyLibrary.dll"
foreach (TypeDefinition type in myLibrary.MainModule.Types) {
    //Writes the full name of a type
    Console.WriteLine (type.FullName);
}

This will not load all the dependencies.



回答2:

You can use Assembly.ReflectionOnlyLoad method to load assembly without executing it.

How to: Load Assemblies into the Reflection-Only Context

Also you need to attach AppDomain.ReflectionOnlyAssemblyResolve as In the reflection-only context, dependencies are not resolved automatically.



回答3:

Okay, I found it. This combination works to get a list of all classes without having to deal with the dependencies:

Assembly assembly = Assembly.LoadFrom(filename); Type[] types = assembly.GetTypes();