对于一个对象,我可以得到它全部采用反射或其他方式的子类? [英] For an object, can I get all its subclasses using reflection or other ways?

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

问题描述

有关的对象,我可以使用反射所有的子类?

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

推荐答案

您可以加载所有类型的组件,然后一一列举,看看哪些实现你的对象的类型。你说的对象所以跌破code样品不适合的接口。此外,该code样品只搜索的对象中声明相同的组件。

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

或作为意见认为,使用这种code样品通过所有加载的程序集的搜索。

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

这两个code样品要求您使用System.Linq的增加;

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

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

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