获取类型的继承树 [英] Get inheritance tree of type

查看:82
本文介绍了获取类型的继承树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
要使用C#的反射得到父类

我想找到获得在C#中使用反射某种类型的继承树的简单方法。

I am trying to find an easy way of getting the inheritance tree of a certain type using reflection in C#.

让我们说,我有以下的类;

Let's say that I have the following classes;

public class A
{ }

public class B : A
{ }

public class C : B
{ }

我如何使用在类型'C'反射来决定其超类是'B',谁又将来自'A'等等?我知道,我可以用'IsSubclassOf()',但是让我们假设,我不知道我要寻找的超类。

How do I use reflection upon type 'C' to determine that its superclass is 'B', who in turn comes from 'A' and so on? I know that I can use 'IsSubclassOf()', but let's assume that I don't know the superclass that I am looking for.

推荐答案

要得到一个类型的直接家长,您可以使用 Type.BaseType 财产。您可以反复拨打 BASETYPE ,直到它返回走了一个类型的继承层次。

To get a type's immediate parent, you can use the Type.BaseType property. You can iteratively call BaseType until it returns null to walk up a type's inheritance hierarchy.

例如:

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



请注意,这不是有效的使用 System.Object的作为终点,因为不是所有的类型(例如,接口类型)继承它。

Do note that it isn't valid to use System.Object as the end-point because not all types (for example, interface types) inherit from it.

这篇关于获取类型的继承树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆