问题描述
我可以找到所有类似于
的基本子类的类var subclasses = Assembly .GetAssembly(typeof(BaseClass)) .GetTypes() .Where(t => t.IsSubclassOf(typeof(BaseClass)))
现在,如何仅选择最专业的子类?也就是说,叶子是没有自己的子类的叶子节点.
推荐答案
subclasses.Where(c => !subclasses.Any(c2 => c == c2.BaseType))
这将更快,您是您制作的木制标本.
这仅是因为BaseClass在同一组件中;否则,它将不一致地捕获从不同组件中的中间类继承的中间类.
更通用的解决方案是对其他每个子类检查IsAssignableFrom.
问题描述
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.