C# 9 新的 "nested switch expression"与关系模式

标签 c# c#-9.0

https://devblogs.microsoft.com/dotnet/c-9-0-on-the-record/#relational-patterns有一个使用“嵌套开关表达式”的例子:

DeliveryTruck t when t.GrossWeightClass switch
{
    > 5000 => 10.00m + 5.00m,
    < 3000 => 10.00m - 2.00m,
    _ => 10.00m,
},

代替:

    DeliveryTruck t when t.GrossWeightClass > 5000 => 10.00m + 5.00m,
    DeliveryTruck t when t.GrossWeightClass < 3000 => 10.00m - 2.00m,
    DeliveryTruck _ => 10.00m,

但我无法让它工作...我的完整代码:

public class DeliveryTruck {
    public int GrossWeightClass { get; set; }
}

public class Class1 {
    public decimal CalculateTollOriginal(object vehicle) =>
        vehicle switch
        {
            DeliveryTruck t when (t.GrossWeightClass > 5000) => 10.00m + 5.00m,
            DeliveryTruck t when (t.GrossWeightClass < 3000) => 10.00m - 2.00m,
            DeliveryTruck t => 10.00m,

            { } => throw new System.ArgumentException(message: "Not a known vehicle type", paramName: nameof(vehicle)),
            null => throw new System.ArgumentNullException(nameof(vehicle))
        };

    public decimal CalculateTollNestedSwitch(object vehicle) =>
        vehicle switch
        {
            DeliveryTruck t when t.GrossWeightClass switch
            {
                > 5000 => 10.00m + 5.00m,
                < 3000 => 10.00m - 2.00m,
                _ => 10.00m,
            },

            { } => throw new System.ArgumentException(message: "Not a known vehicle type", paramName: nameof(vehicle)),
            null => throw new System.ArgumentNullException(nameof(vehicle))
        };

}

我在 dotnet 5.0.100 上遇到编译错误:

C:\Users\pkruk\source\repos\CSharp9\PatternMatching2_NestedSwitch.cs(29,14): error CS1003: Syntax error, '=>' expected [C:\Users\pkruk\source\repos\CSharp9\CSharp9.csproj]
C:\Users\pkruk\source\repos\CSharp9\PatternMatching2_NestedSwitch.cs(29,14): error CS1525: Invalid expression term ',' [C:\Users\pkruk\source\repos\CSharp9\CSharp9.csproj]

我做错了吗?

最佳答案

你需要的是

public decimal CalculateTollNestedSwitch(object vehicle) => vehicle switch
{
    DeliveryTruck t => t.GrossWeightClass switch
    {
        > 5000 => 10.00m + 5.00m,
        < 3000 => 10.00m - 2.00m,
        _ => 10.00m,
    },

    { } => throw new System.ArgumentException(message: "Not a known vehicle type", paramName: nameof(vehicle)),
    null => throw new System.ArgumentNullException(nameof(vehicle))
};

关于C# 9 新的 "nested switch expression"与关系模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64928104/

相关文章:

c# - 广域网通讯

c# - 每次页面加载时都会触发按钮的 OnClick 事件

c# - 制作 ToolStripMenuItem.Selected = true 的最简单方法

c# - "default"通用约束有什么作用?

没有 csproj 的 C# 9 顶级程序?

c# - 在 WPF 中打印

c# - StackExchange.Redis StringSet 最大数组大小

c# - C# 9 中的 Init-Only 和 ReadOnly 有什么区别?

c# - 如何在 C# 9 中将记录转换为元组

c# - 我如何使 .net5 C#9 默认目标框架 VS2019