如何使用 .NET 反射查找类的所有直接子类 [英] How to find all direct subclasses of a class with .NET Reflection

查看:45
本文介绍了如何使用 .NET 反射查找类的所有直接子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下类层次结构:基类 A、从 A 继承的类 B 和 C 以及从 B 继承的类 D.

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 {...}

我可以使用以下代码查找 A 的所有子类,包括 D:

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

但我只需要找到 A 的直接子类(例如 B 和 C),并排除所有不是从 A 直接继承的类(例如 D).知道怎么做吗?

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?

推荐答案

对于每种类型,检查是否

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

这篇关于如何使用 .NET 反射查找类的所有直接子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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