开发者

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

开发者 https://www.devze.com 2022-12-09 01:40 出处:网络
The issue appears is when I have a class implementing an interface, and extending a class which implements an interface:

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 I开发者_如何学JAVASome{}
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). As MSDN I can't assume the order of the interfaces in the array, hence I'm lost. The method typeof(Some).GetInterfaceMap() does not distinguish them either.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号