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

查看:102
本文介绍了给定一个基类,我如何找到它的最专业的子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以找到所有属于BaseClass子类的类

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))

如果您创建BaseType的HashSet,这将更快.

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

这仅适用于因为BaseClass在同一程序集中;否则,它将错误地捕获从另一个程序集中的中间类继承的中间类.
更通用的解决方案是将IsAssignableFrom与其他所有子类进行比较.

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.

这篇关于给定一个基类,我如何找到它的最专业的子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆