簡體   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