gpt4 book ai didi

c# - 如何获取类扩展的所有类的 Type[]

转载 作者:行者123 更新时间:2023-11-30 22:46:36 25 4
gpt4 key购买 nike

您可以执行 Type[] interfaces = typeof(MyClass).GetInterfaces(); 来获取类实现实现的所有内容的列表。

我想知道是否有办法爬取“扩展”树以查看类继承的所有基类型,即抽象类等?

最佳答案

您可以使用Type.BaseType从顶级类型遍历到最基本类型,直到基本类型到达object

像这样:

abstract class A { }
class B : A { }
class C : B { }

public static void Main(string[] args)
{
var target = typeof(C);

var baseTypeNames = GetBaseTypes(target).Select(t => t.Name).ToArray();

Console.WriteLine(String.Join(" : ", baseTypeNames));
}

private static IEnumerable<Type> GetBaseTypes(Type target)
{
do
{
yield return target.BaseType;

target = target.BaseType;
} while (target != typeof(object));
}

关于c# - 如何获取类扩展的所有类的 Type[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2559470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com