获取 class 继承自并在 C# 中实现的所有类型和接口

Get all types and interfaces a class inherits from and implements in C#

我看到这个问题和我的很相似:

How to find all the types in an Assembly that Inherit from a Specific Type C#

但是,如果我的 class 也实现了多个接口怎么办:

class MyClass: MyBaseClass, IMyInterface1, IMyInterface2

我能否以某种方式获取所有 MyClass 工具的数组,而不是一个一个地获取?

对于接口你可以调用 Type.GetInterfaces()

如果您对所有基本类型和接口感兴趣,您可以使用:

static Type[] BaseTypesAndInterfaces(Type type) 
{
    var lst = new List<Type>(type.GetInterfaces());

    while (type.BaseType != null) 
    {
        lst.Add(type.BaseType);
        type = type.BaseType;
    }

    return lst.ToArray();
}

像这样使用它:

var x = BaseTypesAndInterfaces(typeof(List<MyClass>));

甚至可以使其基于泛型

static Type[] BaseTypesAndInterfaces<T>() 
{
    Type type = typeof(T);

    var lst = new List<Type>(type.GetInterfaces());

    while (type.BaseType != null) 
    {
        lst.Add(type.BaseType);
        type = type.BaseType;
    }

    return lst.ToArray();
}

var x = BaseTypesAndInterfaces<MyClass>();

但它可能没那么有趣(因为通常你 "discover" MyClass 在运行时,所以你不能轻易地使用它的泛型方法)

如果要将接口与基类型组合成一个数组,可以这样做:

var t = typeof(MyClass);
var allYourBase = new[] {t.BaseType}.Concat(t.GetInterfaces()).ToArray();

请注意,您的数组将包含所有碱基,包括 System.Object。这不适用于 System.Object,因为它的基本类型是 null.

您可以使用类似的方法一次性完成所有操作:

var allInheritance = type.GetInterfaces().Union(new[] { type.BaseType});

实例:http://rextester.com/QQVFN51007

这是我使用的扩展方法:

public static IEnumerable<Type> EnumInheritance(this Type type)
{
    while (type.BaseType != null)
        yield return type = type.BaseType;
    foreach (var i in type.GetInterfaces())
        yield return i;
}