获取类型的继承树

A.R*_*.R. 14 c# reflection inheritance

可能重复:
使用C#上的Reflection获取父类

我试图找到一种使用C#中的反射获取某种类型的继承树的简单方法.

假设我有以下课程;

public class A
{ }

public class B : A
{ }

public class C : B
{ }
Run Code Online (Sandbox Code Playgroud)

我如何在类型'C'上使用反射来确定它的超类是'B',谁又来自'A'等等?我知道我可以使用'IsSubclassOf()',但我们假设我不知道我正在寻找的超类.

Ani*_*Ani 24

要获取类型的直接父级,可以使用该Type.BaseType属性.您可以迭代调用,BaseType直到它返回null到一个类型的继承层次结构.

例如:

public static IEnumerable<Type> GetInheritanceHierarchy
    (this Type type)
{
    for (var current = type; current != null; current = current.BaseType)
        yield return current;
}
Run Code Online (Sandbox Code Playgroud)

请注意,使用它System.Object作为终点是无效的,因为并非所有类型(例如,接口类型)都从它继承.