How to find all direct subclasses of a class with .NET Reflection

烂漫一生 提交于 2020-01-01 07:30:10

问题


Consider the following classes hierarchy: base class A, classes B and C inherited from A and class D inherited from B.

public class A     {...}
public class B : A {...}
public class C : A {...}
public class D : B {...}

I can use following code to find all subclasses of A including D:

var baseType = typeof(A);
var assembly = typeof(A).Assembly;
var types = assembly.GetTypes().Where(t => t.IsSubclassOf(baseType));

But I need to find only direct subclasses of A (B and C in example) and exclude all classes not directly inherited from A (such as D). Any idea how to do that?


回答1:


For each of those types, check if

type.BaseType == typeof(A)

Or, you can put it directly inline:

var types = assembly.GetTypes().Where(t => t.BaseType == typeof(baseType));



回答2:


Use Type.BaseType for that. From the documentation:

The base type is the type from which the current type directly inherits. Object is the only type that does not have a base type, therefore null is returned as the base type of Object.




回答3:


Just compare them appropriately:

var types = assembly.GetTypes().Where(t => t.BaseType == baseType);


来源:https://stackoverflow.com/questions/16038819/how-to-find-all-direct-subclasses-of-a-class-with-net-reflection

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