查找所有父类型(基类和接口)

我希望能够找到特定类型的所有父类型(基类和接口)。

EG如果我有

class A : B, C { } class B : D { } interface C : E { } class D { } interface E { } 

我想看到A BCD和E和对象

什么是最好的方法呢? 是否有reflection方法来做这个或我需要做自己的东西。

==== ====编辑

这样的事情呢?

 public static IEnumerable ParentTypes(this Type type) { foreach (Type i in type.GetInterfaces()) { yield return i; foreach (Type t in i.ParentTypes()) { yield return t; } } if (type.BaseType != null) { yield return type.BaseType; foreach (Type b in type.BaseType.ParentTypes()) { yield return b; } } } 

我有点希望自己不必自己做,但是哦。

更一般的解决方案

 public static bool InheritsFrom(this Type type, Type baseType) { // null does not have base type if (type == null) { return false; } // only interface or object can have null base type if (baseType == null) { return type.IsInterface || type == typeof(object); } // check implemented interfaces if (baseType.IsInterface) { return type.GetInterfaces().Contains(baseType); } // check all base types var currentType = type; while (currentType != null) { if (currentType.BaseType == baseType) { return true; } currentType = currentType.BaseType; } return false; } 

或实际获取所有父类型:

 public static IEnumerable GetParentTypes(this Type type) { // is there any base type? if (type == null) { yield break; } // return all implemented or inherited interfaces foreach (var i in type.GetInterfaces()) { yield return i; } // return all inherited types var currentBaseType = type.BaseType; while (currentBaseType != null) { yield return currentBaseType; currentBaseType= currentBaseType.BaseType; } } 

要获取由类型实现的接口,请使用Type.GetInterfaces 。 要查看其类层次结构,可以迭代地使用Type.BaseType直到遇到null -reference(通常这会在您点击System.Object之后发生,但不一定 – 例如,接口类型的基类型将直接为null )。

AC#扩展方法为懒:

 ///  /// Extension method to check the entire inheritance hierarchy of a /// type to see whether the given base type is inherited. ///  /// The Type object this method was called on /// The base type to look for in the /// inheritance hierarchy /// True if baseType is found somewhere in the inheritance /// hierarchy, false if not public static bool InheritsFrom(this Type t, Type baseType) { Type cur = t.BaseType; while (cur != null) { if (cur.Equals(baseType)) { return true; } cur = cur.BaseType; } return false; } 

对于接口, typeof(A).GetInterfaces() (此处记录: http : //msdn.microsoft.com/en-us/library/system.type.getinterfaces.aspx )。

对于基类, typeof(A).BaseType (此处记录: http : //msdn.microsoft.com/en-us/library/system.type.basetype.aspx )。

递归呼叫,洗涤,冲洗,重复。

 public static bool IsSubclassOfTypeOrInterface(this Type type, Type ofTypeOrInterface) { if (type == null) { throw new ArgumentNullException("type"); } if (ofTypeOrInterface == null) { throw new ArgumentNullException("ofTypeOrInterface"); } return ofTypeOrInterface.IsInterface ? type.GetInterfaces().Contains(ofTypeOrInterface) : type.IsSubclassOf(ofTypeOrInterface); }