Getting all types that implement an interface

前端 未结 17 1012
不思量自难忘°
不思量自难忘° 2020-11-22 00:34

Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?

This is what I want to re-

17条回答
  •  广开言路
    2020-11-22 01:36

    I see so many overcomplicated answers here and people always tell me that I tend to overcomplicate things. Also using IsAssignableFrom method for the purpose of solving OP problem is wrong!

    Here is my example, it selects all assemblies from the app domain, then it takes flat list of all available types and checks every single type's list of interfaces for match:

    public static IEnumerable GetImplementingTypes(this Type itype) 
        => AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes())
               .Where(t => t.GetInterfaces().Contains(itype));
    

提交回复
热议问题