如何使用模式匹配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
相关产品推荐
相关产品推荐

