【问题标题】:.NET - Getting all implementations of a generic interface?.NET - 获取通用接口的所有实现?
【发布时间】:2011-08-16 11:49:39
【问题描述】:

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

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

谁能解释我如何修改该方法?

【问题讨论】:

    标签: c# .net generics reflection interface


    【解决方案1】:

    你可以这样使用:

    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 中它不起作用,因为某些库无法加载。

    【讨论】:

    • 有没有办法绕过 TypeLoader 异常?
    • 你可以尝试捕捉它。但是当我尝试时,linqpad 崩溃了。
    • GetInterfaces() 不返回由父类实现的接口,是吗?我是否需要递归查看父类,直到我点击typeof(System.Object)
    • @DavidPfeffer 它包括继承的接口:GetInterfaces() 返回“当前Type实现或继承的所有接口。”
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 2021-07-08
      • 1970-01-01
      相关资源
      最近更新 更多