2009-10-23 58 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); 
} 
相關問題