Get type inheritance tree

Possible duplicate:
To get the parent class using Reflection in C #

I am trying to find an easy way to get an inheritance tree of a specific 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 to use type C reflection to determine that its superclass is “B”, which in turn comes from “A”, etc.? I know that I can use IsSubclassOf (), but let me assume that I do not know the superclass I'm looking for.

+9
source share
2 answers

To get the type of the immediate parent, you can use the Type.BaseType property. You can iteratively call BaseType until it returns null in order to approach the type inheritance hierarchy.

For instance:

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

Note that it is not permissible to use System.Object as the endpoint, because not all types (for example, interface types) inherit from it.

+19
source

An object of type System.Type has a property called BaseType , which returns "the type from which the current System.Type is directly inherited." You can go through this BaseType chain until you get null , after which you know you have reached System.Object .

+3
source

Source: https://habr.com/ru/post/906406/


All Articles