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

如何在C#中递归获取继承泛型类的泛型实参?

获取泛型类型继承链中的实际类型参数

要从Ins的Type对象中按Gen1<T1,T2>的顺序获取MyObject和MyInterface,需要遍历类型的继承链,逐层解析泛型参数的实际映射关系——因为Gen2继承Gen1时已经将T1固定为MyObject,而Ins又将Gen2的T2固定为MyInterface,必须通过映射替换才能拿到最终的实际类型。

工具方法实现

下面是一个扩展方法,能递归解析泛型继承链中的所有实际类型参数,保证顺序与最底层泛型基类的参数顺序一致:

using System;
using System.Collections.Generic;
using System.Linq;

public static class TypeExtensions
{
    public static IEnumerable<Type> GetBaseGenericActualArguments(this Type derivedType)
    {
        // 找到最底层的泛型基类(这里是Gen1)
        var baseGenericType = derivedType;
        while (baseGenericType.BaseType != null && baseGenericType.BaseType.IsGenericType)
        {
            baseGenericType = baseGenericType.BaseType;
        }

        // 从派生类向上遍历,构建泛型参数到实际类型的映射表
        var typeParameterMap = new Dictionary<Type, Type>();
        var currentType = derivedType;
        while (currentType != baseGenericType)
        {
            var genericDef = currentType.GetGenericTypeDefinition();
            var actualArgs = currentType.GetGenericArguments();
            var typeParams = genericDef.GetGenericArguments();

            for (int i = 0; i < typeParams.Length; i++)
            {
                typeParameterMap[typeParams[i]] = actualArgs[i];
            }

            currentType = currentType.BaseType;
        }

        // 替换基类泛型参数中的类型变量,得到实际类型列表
        return baseGenericType.GetGenericArguments()
            .Select(arg => typeParameterMap.TryGetValue(arg, out var mappedType) ? mappedType : arg);
    }
}

测试代码

// 定义你的类结构
class MyObject {}
interface MyInterface {}
class Gen1<T1, T2> {}
class Gen2<T2>: Gen1<MyObject, T2> {}
class Ins: Gen2<MyInterface> {}

public class Program
{
    public static void Main()
    {
        var ins = new Ins();
        Type insType = ins.GetType();
        
        var actualArgs = insType.GetBaseGenericActualArguments().ToList();
        // 输出顺序为 MyObject → MyInterface,与Gen1的泛型参数顺序一致
        foreach (var arg in actualArgs)
        {
            Console.WriteLine(arg.Name);
        }
    }
}

工作原理

  1. 定位底层泛型基类:从Ins开始向上遍历继承链,找到最底层的泛型基类(即Gen1<MyObject, T2>)。
  2. 构建参数映射表:从Ins到Gen2,记录每个泛型类型参数对应的实际类型(比如Gen2<T2>的T2对应MyInterface)。
  3. 替换基类参数:将Gen1的泛型参数中的类型变量(T2)替换为映射表中的实际类型,最终得到按Gen1参数顺序排列的MyObject和MyInterface。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 10:45:14