在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/