在所有程序集中查找类型 [英] Find Types in All Assemblies
问题描述
我需要在网站或 Windows 应用程序的所有程序集中查找特定类型,有没有简单的方法可以做到这一点?就像 ASP.NET MVC 的控制器工厂如何查看控制器的所有程序集一样.
I need to look for specific types in all assemblies in a web site or windows app, is there an easy way to do this? Like how the controller factory for ASP.NET MVC looks across all assemblies for controllers.
谢谢.
推荐答案
有两个步骤可以实现:
AppDomain.CurrentDomain.GetAssemblies()
为您提供当前应用程序域中加载的所有程序集.Assembly
类提供了一个GetTypes()
方法来检索该特定程序集中的所有类型.
- The
AppDomain.CurrentDomain.GetAssemblies()
gives you all assemblies loaded in the current application domain. - The
Assembly
class provides aGetTypes()
method to retrieve all types within that particular assembly.
因此您的代码可能如下所示:
Hence your code might look like this:
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Type t in a.GetTypes())
{
// ... do something with 't' ...
}
}
要查找特定类型(例如,实现给定接口、从共同祖先继承或其他任何类型),您必须过滤掉结果.如果您需要在应用程序的多个位置执行此操作,最好构建一个提供不同选项的帮助程序类.例如,我常用的命名空间前缀过滤器、接口实现过滤器和继承过滤器.
To look for specific types (e.g. implementing a given interface, inheriting from a common ancestor or whatever) you'll have to filter-out the results. In case you need to do that on multiple places in your application it's a good idea to build a helper class providing different options. For example, I've commonly applied namespace prefix filters, interface implementation filters, and inheritance filters.
For detailed documentation have a look into MSDN here and here.
这篇关于在所有程序集中查找类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!