Getting all types that implement an interface

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

    To find all types in an assembly that implement IFoo interface:

    var results = from type in someAssembly.GetTypes()
                  where typeof(IFoo).IsAssignableFrom(type)
                  select type;
    

    Note that Ryan Rinaldi's suggestion was incorrect. It will return 0 types. You cannot write

    where type is IFoo
    

    because type is a System.Type instance, and will never be of type IFoo. Instead, you check to see if IFoo is assignable from the type. That will get your expected results.

    Also, Adam Wright's suggestion, which is currently marked as the answer, is incorrect as well, and for the same reason. At runtime, you'll see 0 types come back, because all System.Type instances weren't IFoo implementors.

提交回复
热议问题