.NET: get all classes derived from a specific class

I have a custom control and several controls derived from it. I need all the classes in the current assembly to be retrieved from the main class and validate their attributes. How to do it?

+4
source share
3 answers
var type = typeof(MainClass); var listOfDerivedClasses = Assembly.GetExecutingAssembly() .GetTypes() .Where(x => x.IsSubclassOf(type)) .ToList(); foreach (var derived in listOfDerivedClasses) { var attributes = derived.GetCustomAttributes(typeof(TheAttribute), true); // etc. } 
+12
source

You can use reflection:

 Type baseType = ... var descendantTypes = from type in baseType.Assembly.GetTypes() where !type.IsAbstract && type.IsSubclassOf(baseType) && type.IsDefined(typeof(TheCustomAttributeYouRequire), true) select type; 

You can go from there.

+1
source

To find the derivatives of the class, they are all defined in another assembly (GetExecutingAssembly does not work), I used:

 var asm = Assembly.GetAssembly(typeof(MyClass)); var listOfClasses = asm.GetTypes().Where(x => x.IsSubclassOf(typeof(MyClass))); 

(split into 2 lines to save scrolling)

0
source

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


All Articles