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

C#如何从实例获取泛型参数以筛选同类型MyClass<T>实例

C# 获取泛型实例的泛型参数类型解决方案

省略号位置代码

你可以通过反射拿到item1对应的泛型参数类型,代码如下:

Type itemType = item1.GetType();
// 校验当前实例是否为MyClass<T>的构造类型
if (!itemType.IsGenericType || itemType.GetGenericTypeDefinition() != typeof(MyClass<>))
{
    throw new InvalidOperationException("当前实例不属于MyClass<T>类型");
}
// 拿到对应的泛型参数类型item1_T
Type item1_T = itemType.GetGenericArguments()[0];

后续过滤逻辑修正

注意:C#中OfType<T>的泛型参数必须在编译期确定,你原本计划直接将运行时获取的item1_T作为泛型参数传入OfType的写法无法通过编译,需要调整为运行时类型判断的过滤逻辑:

var subset = list.Where(x => 
{
    var xType = x.GetType();
    return xType.IsGenericType
        && xType.GetGenericTypeDefinition() == typeof(MyClass<>)
        && xType.GetGenericArguments()[0] == item1_T;
}).ToList();
var item2 = subset[random.Next(subset.Count)];

内容的提问来源于stack exchange,提问作者Martien de Jong

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 06:48:03