gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:12:39 24 4
gpt4 key购买 nike

如何编写 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",
4 => "four",
5 => "five",
_ => "unknown",
};

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

最佳答案

C# 9 支持以下内容:

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

或者:

var switchValue = 3;
var resultText = switchValue switch
{
>= 1 and <= 3 => "one, two, or three",
4 => "four",
5 => "five",
_ => "unknown",
};

Source


对于旧版本的 C#,我使用以下扩展方法:

public static bool In<T>(this T val, params T[] vals) => vals.Contains(val);

像这样:

var switchValue = 3;
var resultText = switchValue switch
{
var x when x.In(1, 2, 3) => "one, two, or three",
4 => "four",
5 => "five",
_ => "unknown",
};

when x == 1 || 更简洁一点x == 2 || x == 3 并且比 when new [] {1, 2, 3}.Contains(x) 具有更自然的顺序。

关于C# 8 switch 表达式,具有相同结果的多个案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56676260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com