Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a list of child classes with reflection in .NET 3.5

At runtime, I would like to specify a parent class, and then the program would generate a list of all children classes (of however many generations). For example, if I had Entity as a parent, and Item:Entity and Actor:Entity, there would be two strings, "Actor" and "Item".

I see that System.Reflection.TypeInfo is exactly what I am looking for. However, it appears this is exclusive to .NET 4.5, and my environment is unfortunately stuck at 3.5.

Is there an alternative way to do this in .NET 3.5, or should I consider an upgrade?

like image 771
Kyle Baran Avatar asked Dec 16 '22 16:12

Kyle Baran


1 Answers

var pType = typeof(Entity);
IEnumerable<string> children = Enumerable.Range(1, iterations)
   .SelectMany(i => Assembly.GetExecutingAssembly().GetTypes()
                    .Where(t => t.IsClass && t != pType
                            && pType.IsAssignableFrom(t))
                    .Select(t => t.Name));

Demo

like image 130
Tim Schmelter Avatar answered Mar 23 '23 03:03

Tim Schmelter