Why does Assembly.GetTypes() require references?

别说谁变了你拦得住时间么 提交于 2020-03-14 11:08:30

问题


I want to get all of the types from my assembly, but I don't have the references, nor do I care about them. What does finding the interface types have to do with the references? and is there a way for me to get around this?

Assembly assembly = Assembly.LoadFrom(myAssemblyPath);
Type[] typeArray = assembly.GetTypes();

Throws: FileNotFoundException Could not load file or assembly 'Some referenced assembly' or one of its dependencies. The system cannot find the file specified.


回答1:


Loading an assembly requires all of its dependencies to be loaded as well, since code from the assembly can be executed after it's loaded (it doesn't matter that you don't actually run anything but only reflect on it).

To load an assembly for the express purpose of reflecting on it, you need to load it into the reflection-only context with e.g. ReflectionOnlyLoadFrom. This does not require loading any referenced assemblies as well, but then you can't run code and reflection becomes a bit more awkward than what you 're used to at times.




回答2:


It seems to be a duplicate of Get Types defined in an assembly only, where the solution is:

public static Type[] GetTypesLoaded(Assembly assembly)
{
    Type[] types;
    try
    {
        types = assembly.GetTypes();
    }
    catch (ReflectionTypeLoadException e)
    {
        types = e.Types.Where(t => t != null).ToArray();
    }

    return types;    
}



回答3:


In order to load the assembly, it's necessary to load the assembly's dependencies. If, for example, your assembly contains a type that returns an XmlNode then you will have to load System.Xml.dll




回答4:


An alternative to using the reflection only context might be Mono.Cecil by Jb Evain which is also available via NuGet.

ModuleDefinition module = ModuleDefinition.ReadModule(myAssemblyPath);
Collection<TypeDefinition> types = module.Types;


来源:https://stackoverflow.com/questions/8073432/why-does-assembly-gettypes-require-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!