mti*_*ijn 74

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

class A
{}
...
typeof(A).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(A)));
Run Code Online (Sandbox Code Playgroud)

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

var subclasses =
from assembly in AppDomain.CurrentDomain.GetAssemblies()
    from type in assembly.GetTypes()
    where type.IsSubclassOf(typeof(A))
    select type
Run Code Online (Sandbox Code Playgroud)

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

  • 要对接口而不是对象/类执行相同的操作,请将 where 行更改为 `where typeof(IMyInterface).IsAssignableFrom(type) && type.IsClass` ([原始问题](http://stackoverflow.com/ questions/26733/getting-all-types-that-implement-an-interface-with-c-sharp-3-0))。 (2认同)

joe*_*ish 9

子类意味着接口?是:

this.GetType().GetInterfaces()
Run Code Online (Sandbox Code Playgroud)

子类意味着基类型?好吧,c#只能有一个基类

子类意味着从您的类继承的所有类?是:

编辑:(谢谢vcsjones)

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

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

  • "子类意味着接口" - 抱歉,但这没有意义 (14认同)
  • 您给“子类”一词的定义比实际多了两个。 (2认同)