Getting all types that implement an interface

前端 未结 17 1336
不思量自难忘°
不思量自难忘° 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条回答
  •  猫巷女王i
    2020-11-22 01:31

    Other answer were not working with a generic interface.

    This one does, just replace typeof(ISomeInterface) by typeof (T).

    List types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())
                .Where(x => typeof(ISomeInterface).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
                .Select(x => x.Name).ToList();
    

    So with

    AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())
    

    we get all the assemblies

    !x.IsInterface && !x.IsAbstract
    

    is used to exclude the interface and abstract ones and

    .Select(x => x.Name).ToList();
    

    to have them in a list.

提交回复
热议问题