C#中能否对泛型类型参数应用模式匹配?
用模式匹配重写泛型类型判断代码的可行方案
你尝试的switch写法编译失败,是因为typeof(DateTime)属于Type实例,并非编译时常量,不符合早期C#版本中switch case的常量要求。不过现在有几种可行的模式匹配写法:
方案1:利用默认值的类型模式匹配(C# 8+)
通过default(E)获取类型的默认值,直接用类型模式匹配,写法简洁直观:
public void SayType<T,E>(Func<T, E> f) { var dataType = default(E) switch { DateTime _ => "date/time", string _ => "text", int _ => "whole number", _ => string.Empty }; Console.WriteLine($"type identified as {dataType}"); }
注意:如果E是可空值类型(比如int?),default(E)会是null,无法匹配到对应的非可空值类型case,这种场景下推荐用下面的方案。
方案2:带when条件的switch表达式(C# 8+)
直接对typeof(E)进行匹配,通过when子句做类型比较,兼容性更强,能覆盖可空值类型场景:
public void SayType<T,E>(Func<T, E> f) { var dataType = typeof(E) switch { _ when typeof(E) == typeof(DateTime) => "date/time", _ when typeof(E) == typeof(string) => "text", _ when typeof(E) == typeof(int) => "whole number", _ => string.Empty }; Console.WriteLine($"type identified as {dataType}"); }
也可以写成更清晰的捕获变量形式:
var dataType = typeof(E) switch { Type t when t == typeof(DateTime) => "date/time", Type t when t == typeof(string) => "text", Type t when t == typeof(int) => "whole number", _ => string.Empty };
关于你提到的泛型模式匹配提案
那份提案讨论的是在泛型场景下扩展模式匹配的能力,现在C#已经实现了其中的核心功能——比如允许在泛型方法中使用类型模式匹配default(E),或者结合when条件处理类型比较,上面的方案就是基于这些已落地的特性实现的。
内容的提问来源于stack exchange,提问作者NeilMacMullen
相关产品推荐
相关产品推荐

