How to get all types in a referenced assembly?

后端 未结 3 946
盖世英雄少女心
盖世英雄少女心 2020-12-09 14:51

For whatever reason, I can\'t seem to get the list of types in a referenced assembly. Not only that, I can\'t even seem to be able to get to this referenced assembly.

3条回答
  •  情深已故
    2020-12-09 15:42

    The method GetReferencedAssemblies basically optimize the discovery process on your assembly, skipping those assemblies that you don't have an explicit reference in your main assembly.

    Let's say that you have a project B and a project C that is referencing project B. Now you create a new project A that has a reference to C(not to B)

    When you call Assembly.Load("C path").GetReferenceAssemblies it will return just B if you never made a reference to a class, enum, interface ... that was part of the C assembly.

    As a workaround solution, you can create dummies instances of classes that are present in C.

    Assembly.C.Class1 dummyInstance = new Assemply.C.Class1();
    

    Personally, I used this solution in case you need to separate in a Core project all your interfaces, and in Core.Proj1 to flag your classes with the interfaces used in Core for a later discovery in your main assembly. Take in mind that reflection has an impact on the performance once you are loading multiple assemblies, so don't end with a solution making a discovery on a directory and loading all assemblies to get the types you need. So from that point, you can continue with the code that @jason suggested

    foreach(var ....)
      Assembly assembly = Assembly.Load(assemblyName);
        foreach (var type in assembly.GetTypes()) {
            Console.WriteLine(type.Name);
    

提交回复
热议问题