You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何递归查找类型完整层级,包含开放泛型及其实现?

问题描述

给定一个类类型,需获取其完整类型层级(包含基类和派生类),核心要求是双向结果中必须包含开放泛型类型。

示例场景:
存在以下类定义:

  • class A
  • B<T>: A
  • C: B<int>
  • D<T>: C
  • E: D<int>

调用DiscoverTypeTree(typeof(C))时,预期结果为:

  • 父类型列表:[A, B<>, B<int>]
  • 派生类型列表:[D<>, D<int>, E](派生类型需递归包含所有子类型)

当前问题:无法稳定同时获取开放泛型类型及其具体实现,仅能拿到具体类型,遗漏了开放泛型(实际得到[A,B<int>]和[D<int>,E])。

现有代码(基于C#13,目标框架.NET8,本地函数实现)
var hierarchies = new Dictionary<Type, LinkedList<Type>>();
var derivedTypes = new Dictionary<Type, HashSet<Type>>();
void discoverHierarchy<T>()
    where T : class {
    void _discover(Type type) {
        if (!hierarchies.ContainsKey(type)) {
            var hierarchy = new LinkedList<Type>();
            hierarchies.Add(type, hierarchy);

            var t2 = type;
            do {
                _ = hierarchy.AddFirst(t2);
                _discover(t2);
                t2 = t2.BaseType;
            }
            while (t2 is not null && t2 != typeof(object));

            var derived = new List<Type>();
            var def = type.IsGenericTypeDefinition ? type : null;
            if (def is not null && def != type) {
                _discover(def);
            }
            foreach (var t in assemblyTypes) // Cached output of `assembly.GetTypes()`.
            {
                if (t.IsSubclassOf(type)) {
                    derived.Add(t);
                    _discover(t);
                } else {
                    var t3 = t;
                    var list3 = new List<Type>();
                    do {
                        list3.Add(t3);
                        if (t3.BaseType?.IsGenericType is true && t3.BaseType.GetGenericTypeDefinition() == def) {
                            derived.AddRange(list3);
                            foreach (var _t3 in list3) {
                                _discover(_t3);
                            }
                            break;
                        } else {
                            t3 = t3.BaseType;
                        }
                    }
                    while (t3 is not null);
                }
            }
            _ = derivedTypes.TryAdd(type, []);
            derivedTypes[type].AddRange(derived);
        }
    };

    var type = typeof(T);
    _discover(type);
}

内容的提问来源于stack exchange,提问作者ZzZombo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 00:40:59