Why does Assembly.GetTypes() require references?

后端 未结 4 1942
[愿得一人]
[愿得一人] 2021-01-12 16:34

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 refere

相关标签:
4条回答
  • 2021-01-12 16:59

    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.

    0 讨论(0)
  • 2021-01-12 17:07

    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;
    
    0 讨论(0)
  • 2021-01-12 17:14

    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;    
    }
    
    0 讨论(0)
  • 2021-01-12 17:16

    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

    0 讨论(0)
提交回复
热议问题