如何获得所有类型的引用的程序集?如何获得、类型、程序

2023-09-03 15:41:36 作者:时间在走 人心在变

无论出于何种原因,我似乎无法得到引用的组件类型列表。不仅如此,我甚至不能似乎能够获得这个引用程序集。

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.

我试过 AppDomain.CurrentDomain.GetAssemblies(),但它只返回那些已经被加载到内存中的程序集。

I tried AppDomain.CurrentDomain.GetAssemblies(), but it only returns assemblies that have already been loaded into memory.

我试过 Assembly.GetExecutingAssembly()。GetReferencedAssemblies(),但这只是返回的mscorlib。

I tried Assembly.GetExecutingAssembly().GetReferencedAssemblies(), but this just returns mscorlib.

我在想什么?

推荐答案

注意 Assembly.GetReferencedAssemblies 只包括一个特定的组件,如果你确实使用类型中的组件您的程序集(或一个类型,使用依赖于该组件的类型)。它是不够的,仅仅包括在Visual Studio引用列表的组件。这也许解释了与预期的产出区别?我注意到,如果你期待能够获得所有那些在使用反射是不可能的Visual Studio引用列表中的组件;的元数据集不包括有关程序集上给定的程序集是不依赖于任何信息。

Note that Assembly.GetReferencedAssemblies only includes a particular assembly if you actually use a type in that assembly in your assembly (or a type that you use depends on a type in that assembly). It is not enough to merely include an assembly in the list of references in Visual Studio. Maybe this explains the difference in output from what you expect? I note that if you're expecting to be able to get all the assemblies that are in the list of references in Visual Studio using reflection that is impossible; the metadata for the assembly does not include any information about assemblies on which the given assembly is not dependent on.

这是说,一旦你检索到的所有引用的程序集类似于下面的东西应该让你列举了这些组件的所有类型的列表:

That said, once you've retrieved a list of all the referenced assemblies something like the following should let you enumerate over all the types in those assemblies:

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

如果您需要在Visual Studio中引用的程序集,那么你将不得不解析的csproj 文件。为此,检查了 ItemGroup 包含元素参考元素。

If you need the assemblies that are referenced in Visual Studio then you will have to parse the csproj file. For that, check out the ItemGroup element containing Reference elements.

最后,如果你知道一个程序集居住,您可以使用加载它 Assembly.LoadFile ,然后基本上是进行上述列举了生活在装入的类型装配。

Finally, if you know where an assembly lives, you can load it using Assembly.LoadFile and then essentially proceed as above to enumerate over the types that live in that loaded assembly.