.NET - Getting all implementations of a generic interface?

后端 未结 2 771
余生分开走
余生分开走 2020-12-07 00:16

An answer on \" Implementations of interface through Reflection \" shows how to get all implementations of an interface. However, given a generic interface, IInterface

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 01:07

    You can use something like this:

    public static bool DoesTypeSupportInterface(Type type, Type inter)
    {
        if(inter.IsAssignableFrom(type))
            return true;
        if(type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == inter))
            return true;
        return false;
    }
    
    public static IEnumerable TypesImplementingInterface(Type desiredType)
    {
        return AppDomain
            .CurrentDomain
            .GetAssemblies()
            .SelectMany(assembly => assembly.GetTypes())
            .Where(type => DoesTypeSupportInterface(type, desiredType));
    
    }
    

    It can throw a TypeLoadException though but that's a problem already present in the original code. For example in LINQPad it doesn't work because some libraries can't be loaded.

提交回复
热议问题