相关疑难解决方法(0)

c#8开关表达式多个结果相同的情况

如何编写一个开关表达式来支持多个返回相同结果的情况?

对于版本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;
}
Run Code Online (Sandbox Code Playgroud)

当我使用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",
};
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:如何将案例1,2和3变成一个开关案例臂,从而不需要重复该值? …

c# c#-8.0 switch-expression

8
推荐指数
3
解决办法
1100
查看次数

标签 统计

c# ×1

c#-8.0 ×1

switch-expression ×1