【问题标题】:Get inheritance tree of type获取类型的继承树
【发布时间】:2016-05-12 19:05:39
【问题描述】:

可能重复:
To get parent class using Reflection on C#

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

假设我有以下课程;

public class A
{ }

public class B : A
{ }

public class C : B
{ }

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

【问题讨论】:

标签: c# reflection inheritance


【解决方案1】:

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

例如:

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

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

【讨论】:

  • 可以往另一个方向走吗?
  • @rolls,确实如此,但这会给你一整棵树,而不是列表。
【解决方案2】:

System.Type 类型的对象有一个名为 BaseType 的属性,它返回“当前 System.Type 直接继承的类型”。你可以沿着这条BaseTypes 链向上走,直到你得到null,此时你知道你已经到达System.Object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多