2009-10-23 45 views
6

出现的问题是,当我有一个类实现一个接口,并延伸它实现一个接口的类:如何知道接口何时直接实现忽略继承类型的类型?

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

由于typeof运算(一些).GetInterfaces()返回和阵列ISome和ISomeBase,我m无法区分是否实施或继承了ISome(作为ISomeBase)。作为MSDN,我不能假设数组中的接口的顺序,因此我迷路了。 (Some).GetInterfaceMap()方法不区分它们。

+1

为什么这么在意?你想做什么? – 2009-10-23 14:36:19

+1

需要很长时间才能解释,但我想根据自己的接口实现自动注册AutoFac中的服务,因为服务可以扩展,所以我需要区别。 – 2009-10-23 14:45:04

回答

8

你只需要排除的基本类型实现的接口:

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); 
} 
相关问题