对于一个对象,我可以使用反射或其他方式获取其所有子类吗? [英] For an object, can I get all its subclasses using reflection or other ways?

查看:22
本文介绍了对于一个对象,我可以使用反射或其他方式获取其所有子类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个对象,我可以使用反射获取它的所有子类吗?

For an object, can I get all its subclasses using reflection?

推荐答案

您可以加载程序集中的所有类型,然后枚举它们以查看哪些类型实现了您的对象的类型.您说的是对象",因此下面的代码示例不适用于接口.此外,此代码示例仅搜索与声明对象相同的程序集.

You can load all types in the Assembly and then enumerate them to see which ones implement the type of your object. You said 'object' so the below code sample is not for interfaces. Also, this code sample only searches the same assembly as the object was declared in.

class A
{}
...
typeof(A).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(A)));

或者按照评论中的建议,使用此代码示例来搜索所有加载的程序集.

Or as suggested in the comments, use this code sample to search through all of the loaded assemblies.

var subclasses =
from assembly in AppDomain.CurrentDomain.GetAssemblies()
    from type in assembly.GetTypes()
    where type.IsSubclassOf(typeof(A))
    select type

两个代码示例都要求您添加using System.Linq;

Both code samples require you to add using System.Linq;

这篇关于对于一个对象,我可以使用反射或其他方式获取其所有子类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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