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

限于喜欢 提交于 2020-01-04 04:31:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!