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

后端 未结 3 1684
既然无缘
既然无缘 2021-01-21 07:05

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

3条回答
  •  渐次进展
    2021-01-21 07:16

    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

提交回复
热议问题