在.NET 3.5中生成带有反射的子类列表 [英] Generating a list of child classes with reflection in .NET 3.5
问题描述
在运行时,我想指定一个父类,然后程序将生成所有子类的列表(无论是多少代)。例如,如果我有 Entity
作为父级,并且 Item:Entity
和 Actor:实体
,将有两个字符串, Actor和 Item。
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".
我看到了 System.Reflection .TypeInfo
正是我想要的。但是,这似乎是.NET 4.5所独有的,而且我的环境不幸地停留在3.5。
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.
.NET 3.5中是否存在另一种方法来实现此目的,或者我应该考虑升级吗?
Is there an alternative way to do this in .NET 3.5, or should I consider an upgrade?
推荐答案
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));
这篇关于在.NET 3.5中生成带有反射的子类列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!