查找所有组件类型组件、类型

2023-09-04 00:04:44 作者:不爱几个人渣怎知货比三家

我需要寻找特定类型的所有组件在一个网站或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 a GetTypes() 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 =htt​​p://msdn.microsoft.com/en-us/library/system.appdomain.getassemblies.aspx>这里。

For detailed documentation have a look into MSDN here and here.