我很好奇还有其他方法可以用 C# 8 中的新 switch 表达式编写这样的东西吗?
public static object Convert(string str, Type type) =>
type switch
{
_ when type == typeof(string) => str,
_ when type == typeof(string[]) => str.Split(new[] { ',', ';' }),
_ => TypeDescriptor.GetConverter(type).ConvertFromString(str)
};
因为
_ when type == typeof(string)
看起来有点奇怪,尤其是当我们有 type pattern 时和其他非常方便的仪器。
最佳答案
正如其他人所暗示的那样,您实际上需要有一个类型的实例来使用新的类型匹配功能,而不是典型的 System.Type
.如果您想直接在类型上进行匹配,那么您这样做的方式似乎是目前唯一可行的方式。
话虽如此,我认为在这种情况下,标准 switch
语句可能更具可读性:
switch (type)
{
case Type _ when type == typeof(string):
return str;
case Type _ when type == typeof(string[]):
return str.Split(',', ';');
default:
return TypeDescriptor.GetConverter(type).ConvertFromString(str);
}
如果你真的想保留 switch 表达式,你可以通过匹配类型名称来解决这个问题,尽管正如下面的评论者指出的那样,这个选项特别脆弱并且不适用于某些类型(例如 DateTime?
或Nullable<DateTime>
):public static object Convert(string str, Type type) =>
type.Name switch
{
nameof(string) => str,
nameof(string[]) => str.Split(new[] { ',', ';' }),
_ => TypeDescriptor.GetConverter(type).ConvertFromString(str)
};
关于c# - 在 C# 8 中 System.Type 上的开关表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61945211/