Find Types in All Assemblies

后端 未结 4 1013
南笙
南笙 2020-12-05 06:27

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 acr

4条回答
  •  执念已碎
    2020-12-05 06:47

    There are two steps to achieve this:

    • 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.

    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.

提交回复
热议问题