Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For an object, can I get all its subclasses using reflection or other ways?

For an object, can I get all its subclasses using reflection?

like image 589
Adam Lee Avatar asked Jan 19 '12 15:01

Adam Lee


2 Answers

You can load all types in the Assembly and then enumerate them to see which ones implement the type of your object. You said 'object' so the below code sample is not for interfaces. Also, this code sample only searches the same assembly as the object was declared in.

class A {} ... typeof(A).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(A))); 

Or as suggested in the comments, use this code sample to search through all of the loaded assemblies.

var subclasses = from assembly in AppDomain.CurrentDomain.GetAssemblies()     from type in assembly.GetTypes()     where type.IsSubclassOf(typeof(A))     select type 

Both code samples require you to add using System.Linq;

like image 168
mtijn Avatar answered Sep 25 '22 05:09

mtijn


Subclasses meaning interfaces? Yes:

this.GetType().GetInterfaces() 

Subclasses meaning base types? Well, c# can only have one base class

Subclasses meaning all classes that inherit from your class? Yes:

EDIT: (thanks vcsjones)

foreach(var asm in AppDomain.CurrentDomain.GetAssemblies()) {         foreach (var type in asm.GetTypes())         {             if (type.BaseType == this.GetType())                 yield return type;         } } 

And do that for all loaded assemblies

like image 22
joe_coolish Avatar answered Sep 24 '22 05:09

joe_coolish