对于一个对象,我可以使用反射或者其他方式获取它的所有子类吗?

发布于 2024-12-27 16:02:34 字数 31 浏览 1 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空心空情空意 2025-01-03 16:02:34

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

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

或者按照注释中的建议,使用此代码示例搜索所有已加载的程序集。

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

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

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;

高速公鹿 2025-01-03 16:02:34

获取子类:

foreach(var asm in AppDomain.CurrentDomain.GetAssemblies())
{
        foreach (var type in asm.GetTypes())
        {
            if (type.BaseType == this.GetType())
                yield return type;
        }
}

并对所有加载的程序集执行此操作

您还可以获取接口:

this.GetType().GetInterfaces()

而要做相反的操作(获取基类),C# 只能有一个基类。

To get subclasses:

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

You also can get interfaces:

this.GetType().GetInterfaces()

And to do the opposite (get the base class), C# can only have one base class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文