繁体   English   中英

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

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

我看到了这个与我相似的问题:

如何在从特定类型 C# 继承的程序集中查找所有类型

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

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

但它可能不那么有趣(因为通常你在运行时“发现” 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM