【问题标题】:How do I know when an interface is directly implemented in a type ignoring inherited ones?我如何知道接口何时以忽略继承的类型直接实现?
【发布时间】:2010-12-09 11:45:30
【问题描述】:

当我有一个实现接口的类并扩展一个实现接口的类时,就会出现问题:

class Some : SomeBase, ISome {}
class SomeBase : ISomeBase {}
interface ISome{}
interface ISomeBase{}

由于 typeof(Some).GetInterfaces() 返回并带有 ISome 和 ISomeBase 的数组,我无法区分 ISome 是实现还是继承(作为 ISomeBase)。作为 MSDN,我不能假设数组中接口的顺序,因此我迷路了。 typeof(Some).GetInterfaceMap() 方法也不区分它们。

【问题讨论】:

  • 你为什么在乎?你想做什么?
  • 解释的有点长,但是我想根据接口实现在AutoFac中自动注册服务,因为服务可以扩展,所以需要区分一下。

标签: c# reflection interface


【解决方案1】:

你只需要排除基类型实现的接口:

public static class TypeExtensions
{
    public static IEnumerable<Type> GetInterfaces(this Type type, bool includeInherited)
    {
        if (includeInherited || type.BaseType == null)
            return type.GetInterfaces();
        else
            return type.GetInterfaces().Except(type.BaseType.GetInterfaces());
    }
}

...


foreach(Type ifc in typeof(Some).GetInterfaces(false))
{
    Console.WriteLine(ifc);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 2019-08-04
    • 1970-01-01
    相关资源
    最近更新 更多