[英]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.