查找所有组件类型 [英] Find Types in All Assemblies

查看:167
本文介绍了查找所有组件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要寻找特定类型的所有组件在一个网站或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.

这篇关于查找所有组件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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