如何获取引用程序集中的所有类型? [英] How to get all types in a referenced assembly?

查看:41
本文介绍了如何获取引用程序集中的所有类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论出于何种原因,我似乎无法获得引用程序集中的类型列表.不仅如此,我什至无法访问这个引用的程序集.

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 文件.为此,请查看包含 Reference 元素的 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.

这篇关于如何获取引用程序集中的所有类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆