给定一个基类,我怎样才能找到它的最专业的子类?[英] Given a base class how do I find the most specialized subclasses of it?

本文是小编为大家收集整理的关于给定一个基类,我怎样才能找到它的最专业的子类?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我可以找到所有类似于

的基本子类的类
var subclasses = Assembly
   .GetAssembly(typeof(BaseClass))
   .GetTypes()
   .Where(t => t.IsSubclassOf(typeof(BaseClass)))

现在,如何仅选择最专业的子类?也就是说,叶子是没有自己的子类的叶子节点.

推荐答案

subclasses.Where(c => !subclasses.Any(c2 => c == c2.BaseType))

这将更快,您是您制作的木制标本.

这仅是因为BaseClass在同一组件中;否则,它将不一致地捕获从不同组件中的中间类继承的中间类.
更通用的解决方案是对其他每个子类检查IsAssignableFrom.

本文地址:https://www.itbaoku.cn/post/1557165.html

问题描述

I can find all the classes that are subclasses of BaseClass with something like

var subclasses = Assembly
   .GetAssembly(typeof(BaseClass))
   .GetTypes()
   .Where(t => t.IsSubclassOf(typeof(BaseClass)))

Now, how do I select only the most specialized subclasses? That is, the leaf-nodes, the ones with no subclasses of their own.

推荐答案

subclasses.Where(c => !subclasses.Any(c2 => c == c2.BaseType))

This will be faster is you make a HashSet of BaseTypes.

This only works because BaseClass is in the same assembly; otherwise, it would inconrrectly catch intermediate classes which inherit from an intermediate class in a different assembly.
The more general solution would be to check IsAssignableFrom against every other subclass.