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

孤街醉人 提交于 2019-12-19 02:02:36

问题


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). 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.


回答1:


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


来源:https://stackoverflow.com/questions/1613867/how-do-i-know-when-an-interface-is-directly-implemented-in-a-type-ignoring-inher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!