查找所有组件类型 [英] 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.
感谢。
推荐答案
有两个步骤来实现这一点:
There are two steps to achieve this:
- 的
AppDomain.CurrentDomain.GetAssemblies()
为您提供了在当前应用程序域中加载的所有程序集。 - 的
组装
类提供了一个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.
因此您code可能是这样的:
Hence your code might look like this:
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Type t in a.GetTypes())
{
// ... do something with 't' ...
}
}
要查找特定类型(如实现一个给定的接口,从一个共同的祖先或任何继承),你必须筛选出的结果。如果你需要做的是在你的应用程序的多个地方,它是一个好主意,建立一个辅助类,提供了不同的选择。例如,我常用的命名空间preFIX过滤器,接口实现过滤器和过滤器继承
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.
有关详细的文档看看到MSDN 这里和< A HREF =http://msdn.microsoft.com/en-us/library/system.appdomain.getassemblies.aspx>这里。
For detailed documentation have a look into MSDN here and here.
这篇关于查找所有组件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!