获取类型的inheritance树
可能重复:
在C#上使用Reflection获取父类
我试图找到一种使用C#中的reflection获取某种类型的inheritance树的简单方法。
假设我有以下课程;
public class A { } public class B : A { } public class C : B { }
如何在类型’C’上使用reflection来确定其超类是’B’,谁又来自’A’等等? 我知道我可以使用’IsSubclassOf()’,但我们假设我不知道我正在寻找的超类。
要获取类型的直接父级,可以使用Type.BaseType
属性。 您可以迭代地调用BaseType
直到它返回null
来向上移动类型的inheritance层次结构。
例如:
public static IEnumerable GetInheritanceHierarchy (this Type type) { for (var current = type; current != null; current = current.BaseType) yield return current; }
请注意,使用System.Object
作为端点是无效的,因为并非所有类型(例如,接口类型)都从它inheritance。
System.Type
类型的对象具有名为BaseType
的属性,该属性返回“当前System.Type直接inheritance的类型”。 你可以走这条BaseType
链,直到你得到null
,此时你知道你已经到达System.Object
。