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

已知父类实例,如何获取其泛型子类的泛型类型参数?

获取Child泛型参数T的方法

已知Parent类型的对象实际是Child<T>的实例时,完全可以通过反射提取出泛型参数T,具体实现步骤如下:

1. 获取对象的实际运行时类型

先拿到对象的真实类型,而非声明的Parent类型:

Parent targetObj = ...; // 已知实际为Child<T>实例
Type actualType = targetObj.GetType();

2. 验证类型是否为Child的泛型实例

先判断该类型是否是Child<>的构造泛型类型,避免非目标类型导致后续报错:

bool isChildGeneric = actualType.IsGenericType 
                      && actualType.GetGenericTypeDefinition() == typeof(Child<>);

3. 提取泛型参数T

通过GetGenericArguments()方法获取泛型参数数组,由于Child<T>仅定义了一个泛型参数,直接取数组第一个元素即可:

if (isChildGeneric)
{
    Type tType = actualType.GetGenericArguments()[0];
    // 用tType去mapping字典中取值
    if (mapping.TryGetValue(tType, out var mappedValue))
    {
        // 成功获取到对应映射
    }
}

完整示例代码

// 模拟场景:已有Parent对象和映射字典
Parent targetObj = new Child<MyCollection>(); // MyCollection继承自CollectionBase
Dictionary<Type, object> mapping = new Dictionary<Type, object>();
mapping[typeof(MyCollection)] = "测试映射值";

// 提取T并获取映射
Type actualType = targetObj.GetType();
if (actualType.IsGenericType && actualType.GetGenericTypeDefinition() == typeof(Child<>))
{
    Type tType = actualType.GetGenericArguments()[0];
    if (mapping.TryGetValue(tType, out var value))
    {
        Console.WriteLine($"获取到映射值:{value}");
    }
}

注意点

  • 必须先验证类型是否为Child<>的泛型实例,否则针对非目标类型调用GetGenericArguments()会抛出异常。
  • 如果后续Child扩展为多泛型参数(如Child<T1,T2>),需根据实际需求调整GetGenericArguments()的索引位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:20:24