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

如何使用模式匹配switch重写该C#泛型Fetch方法?

用模式匹配switch重写C#泛型Fetch方法

你可以直接针对typeof(ResultType)使用类型模式匹配简化switch逻辑,去掉冗余的when条件,同时精简类型转换步骤,重写后的代码如下:

internal ResultType Fetch<ResultType>(string field)
{
    return typeof(ResultType) switch
    {
        typeof(DateTime) => (ResultType)(object)FetchDateTime(field),
        typeof(DateOnly) => (ResultType)(object)FetchDateOnly(field),
        typeof(bool) => (ResultType)(object)FetchBool(field),
        typeof(decimal) => (ResultType)(object)FetchDecimal(field),
        typeof(string) => (ResultType)(object)FetchString(field),
        typeof(int) => (ResultType)(object)FetchInt(field),
        _ => throw new NotImplementedException($"this[field: {field}]")
    };
}

关键优化点:

  • 直接以typeof(ResultType)作为switch表达式主体,case分支直接匹配目标类型的typeof(XXX)实例,无需额外的when条件判断,代码更简洁直观
  • 每个分支将FetchXXX的返回值先装箱再拆箱为ResultType——由于我们已经通过模式匹配确认了泛型类型与返回值类型一致,这个转换是安全的
  • 移除了原代码中的中间object变量和后续类型检查逻辑,直接通过switch表达式返回结果,逻辑更紧凑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 15:17:14