C# 对于一个对象,我可以使用反射或其他方式获取其所有子类吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8928464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
For an object, can I get all its subclasses using reflection or other ways?
提问by Adam Lee
For an object, can I get all its subclasses using reflection?
对于一个对象,我可以使用反射获取它的所有子类吗?
采纳答案by mtijn
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
Both code samples require you to add using System.Linq;
两个代码示例都需要您添加 using System.Linq;
回答by joe_coolish
Subclasses meaning interfaces? Yes:
子类意味着接口?是的:
this.GetType().GetInterfaces()
Subclasses meaning base types? Well, c# can only have one base class
子类意味着基本类型?好吧,c# 只能有一个基类
Subclasses meaning all classes that inherit from your class? Yes:
子类意味着从您的类继承的所有类?是的:
EDIT: (thanks vcsjones)
编辑:(感谢 vcsjones)
foreach(var asm in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var type in asm.GetTypes())
{
if (type.BaseType == this.GetType())
yield return type;
}
}
And do that for all loaded assemblies
并对所有加载的程序集执行此操作

