Getting all types that implement an interface

前端 未结 17 1209
不思量自难忘°
不思量自难忘° 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:16

    Even better when choosing the Assembly location. Filter most of the assemblies if you know all your implemented interfaces are within the same Assembly.DefinedTypes.

    // We get the assembly through the base class
    var baseAssembly = typeof(baseClass).GetTypeInfo().Assembly;
    
    // we filter the defined classes according to the interfaces they implement
    var typeList = baseAssembly.DefinedTypes.Where(type => type.ImplementedInterfaces.Any(inter => inter == typeof(IMyInterface))).ToList();
    

    By Can Bilgin

提交回复
热议问题