.NET - 获取通用接口的所有实现?

时间:2011-05-01 15:11:36

标签: c# .net generics reflection interface

Implementations of interface through Reflection”的答案显示了如何获得接口的所有实现。但是,给定通用接口IInterface<T>,以下内容不起作用:

var types = TypesImplementingInterface(typeof(IInterface<>))

任何人都可以解释我如何修改该方法吗?

2 个答案:

答案 0 :(得分:21)

您可以使用以下内容:

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<Type> TypesImplementingInterface(Type desiredType)
{
    return AppDomain
        .CurrentDomain
        .GetAssemblies()
        .SelectMany(assembly => assembly.GetTypes())
        .Where(type => DoesTypeSupportInterface(type, desiredType));

}

它可以抛出TypeLoadException,但这是原始代码中已经存在的问题。例如在LINQPad中,它不起作用,因为某些库无法加载。

答案 1 :(得分:1)

它不起作用,因为IInterface<object>(使用System.Object作为示例)不会从“开放”泛型类型IInterface<>继承。 “封闭”泛型类型是根类型,就像IFoo一样。您只能搜索封闭的泛型类型,而不是打开的类型,这意味着您可以找到从IInterface<int>继承的所有内容。 IFoo没有基类,IInterface<object>IInterface<string>等也没有。