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:
- A
- B
- C
- ...
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