Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
262 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...