Get inheritance tree of type

限于喜欢 提交于 2020-01-20 02:40:05

问题


Possible Duplicate:
To get parent class using Reflection on 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
{ }

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.


回答1:


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.

For example:

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

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.




回答2:


An object of type System.Type has a property named BaseType which returns "the type from which the current System.Type directly inherits." You can walk up this chain of BaseTypes until you get null, at which point you know you have reached System.Object.



来源:https://stackoverflow.com/questions/5716896/get-inheritance-tree-of-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!