我如何知道何时在忽略继承的接口的类型中直接实现接口? [英] How do I know when an interface is directly implemented in a type ignoring inherited ones?

查看:102
本文介绍了我如何知道何时在忽略继承的接口的类型中直接实现接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题出现的时候是我有一个实现接口的类,并扩展了一个实现接口的类:

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{}

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

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

这篇关于我如何知道何时在忽略继承的接口的类型中直接实现接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆