c# - 在 C# 8 中 System.Type 上的开关表达式

标签 c# switch-statement c#-8.0

我很好奇还有其他方法可以用 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/

相关文章:

c# - 无法使用 .NET Core 3 预览版 4 编译 C# 8

C# 8 - 枚举上的 CS8605 "Unboxing possibly null value"

c# - EmguCV - 匹配模板

javascript - 如何将资源中的正则表达式模式插入到 string.Format 中?

C# 8 switch 表达式,具有相同结果的多个案例

c++ - 如果 C++ 枚举的 switch 语句中的枚举值 > const N,如何获取?

java - 循环中的 Switch 语句重复次数未知

c# - Winform - 确定鼠标是否离开用户控制

c# - 如何使用 LINQ 查找包含 2 个逗号分隔字符串的匹配项

c# - 在 C# 中使用 enum 和 struct 代替 switch 语句