How to find types that are direct descendants of a base class?

落爺英雄遲暮 提交于 2020-01-14 18:44:12

问题


I need to get all types of an assembly that inherits some base class but only the first descendants. For instance if I have:

class Base
{

}

class FirstClass : Base
{

}

class SecondClass : FirstClass
{

}

Now

var directOnes = assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(Base)));

should return only FirstClass and not SecondClass. Is there a way to find out?


回答1:


Instead of IsSubclassOf() you can use Type.BaseType

e.g.

var directOnes = assembly.GetTypes().Where(t => t.BaseType == (typeof(Base)));

(FYI: I don't think there's a way to find the interfaces that a type directly implements.)



来源:https://stackoverflow.com/questions/16476073/how-to-find-types-that-are-direct-descendants-of-a-base-class

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