Home > Blockchain >  How to get all inherited classes
How to get all inherited classes

Time:07-16

Let's imagine that we have a class called A, and this class is inherited from class B, and also class B inherited from class C. We can extend this sequence as long as we want. How can we get all classes from this sequence? Like:

  1. A
  2. B
  3. C
  4. ...

CodePudding user response:

Try this code:

        Type type = typeof(C);
        while (type.BaseType!=null) 
        {
            type = type.BaseType;
            Console.WriteLine(type.Name);
        }
        // C
        // B
        // A
        // Object

CodePudding user response:

var assemblies = AppDomain.CurrentDomain.GetAssemblies();

foreach (var assembly in assemblies)
    foreach (Type type in assembly.GetTypes())
    {
        if (typeof(A).IsAssignableFrom(type))
            Console.WriteLine(type);
    }

// These can be in various projects / assemblies
class A { }
class B : A { }
class C : A { }
class D : B { }
class E { }
class F : E { }
class G : D { }

Prints:

A
B
C
D
G
  • Related