如何解决C# 8 switch 表达式具有多个具有相同结果的情况?

我开始安装它,但我还没有找到一种方法来使用新语法为单个 switch 部分指定多个单独的 case 标签

但是,您可以创建一个新变量来捕获该值,然后使用条件来表示应该具有相同结果的情况:

var resultText = switchValue switch
{
    var x when
        x == 1 ||
        x == 2 ||
        x == 3 => "one to three",
    4 => "four",
    5 => "five",
    _ => "unkNown",
};

如果您有很多案例要测试,这实际上更简洁,因为您可以在一行中测试一系列值:

var resultText = switchValue switch
{
    var x when x > 0 && x < 4 => "one to three",
    4 => "four",
    5 => "five",
    _ => "unkNown",
};

解决方法

如何编写 switch 表达式以支持返回相同结果的多种情况?

在版本 8 之前的 C# 中,可以这样编写开关:

var switchValue = 3;
var resultText = string.Empty;
switch (switchValue)
{
    case 1:
    case 2:
    case 3:
        resultText = "one to three";
        break;
    case 4:
        resultText = "four";
        break;
    case 5:
        resultText = "five";
        break;
    default:
        resultText = "unkown";
        break;
}

当我使用 C# 版本 8 时,使用表达式语法,就像这样:

var switchValue = 3;
var resultText = switchValue switch
{
    1 => "one to three",2 => "one to three",3 => "one to three",4 => "four",5 => "five",_ => "unknown",};

所以我的问题是:如何将案例 1、2 和 3 变成一个 switch-case-arm,这样就不需要重复该值?

根据“ Rufus L ”的建议更新:

对于我给定的示例,这是有效的。

var switchValue = 3;
var resultText = switchValue switch
{
    var x when (x >= 1 && x <= 3) => "one to three",};

但这并不是我想要完成的。这仍然只是一种情况(带有过滤条件),而不是多种情况产生相同的右手结果。