问题
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?
回答1:
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
回答2:
One possible way would utilize the Type.IsAssignableFrom
method. You would loop over all types, and select those for which it is true.
Basically, it would be something like
Type parent = Type.GetType("Entity");
Type[] types = Assembly.GetExecutingAssembly().GetTypes(); // Maybe select some other assembly here, depending on what you need
Type[] inheritingTypes = types.Where(t => parent.IsAssignableFrom(t));
I don't have a compiler available at this time, so I can't verify it, but it should be mostly correct
来源:https://stackoverflow.com/questions/13896716/generating-a-list-of-child-classes-with-reflection-in-net-3-5