简体   繁体   English

我如何知道何时在忽略继承的类型中直接实现接口?

[英]How do I know when an interface is directly implemented in a type ignoring inherited ones?

The issue appears is when I have a class implementing an interface, and extending a class which implements an interface: 出现的问题是当我有一个实现接口的类,并扩展实现接口的类时:

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

Since typeof(Some).GetInterfaces() returns and array with ISome and ISomeBase, i'm not able to distinguish if ISome is implemented or inherited (as ISomeBase). 由于typeof(Some).GetInterfaces()返回带有ISome和ISomeBase的数组,我无法区分ISome是实现还是继承(如ISomeBase)。 As MSDN I can't assume the order of the interfaces in the array, hence I'm lost. 作为MSDN我不能假设数组中接口的顺序,因此我迷路了。 The method typeof(Some).GetInterfaceMap() does not distinguish them either. 方法typeof(Some).GetInterfaceMap()也不区分它们。

You just need to exclude the interfaces implemented by the base type : 您只需要排除基类型实现的接口:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 枚举类型的接口时,如何仅获得那些直接继承的接口? - When enumerating a type's interfaces how do I get only those that are directly inherited? 如何使用反射确定已实现接口的通用类型? - How do I determine the generic type of an implemented interface using reflection? 我如何找到实现接口的类 - How do I find the class that implemented an interface 如何调用已实现的接口函数 - How do I call an implemented interface function 如何在仅在基类中实现的继承类中调用InvokeMember - How do I InvokeMember in inherited class that is only implemented in base 为什么已经使用另一种类型实现了接口类型的对象,为什么我必须显式实现它呢? - Why do I have to explicitly implement an interface member of type object when the member has already been implemented with another type? 如果我有继承类类型的MethodInfo,如何获取接口的MethodInfo? - How to get MethodInfo of interface, if i have MethodInfo of inherited class type? 如何限制仅由通用类型实现的接口 - How can I restrict an Interface to be implemented by only a generic type 如何知道继承泛型类型的基类型? - How to know the base type of an inherited generic type? 如何直接从 class 调用从接口继承的方法? - How can I call a method inherited from an interface directly from a class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM