C#8开关表达式具有相同结果的多种情况 [英] C# 8 switch expression with multiple cases with same result
问题描述
如何编写switch表达式以支持多个返回相同结果的案例?
How can a switch expression be written to support multiple cases returning the same result?
对于版本8之前的C#,可能会这样编写一个开关:
With C# prior to version 8, a switch may be written like so:
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时,就像这样:
When I am using the C# version 8, with the expression syntax, it's like so:
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变成仅一个开关案例臂,从而不需要重复该值?
So my question is: How to turn the cases 1, 2 and 3 to just one switch-case-arm so the value doesn't need to be repeated?
根据" Rufus L "中的建议进行更新:
Update per suggestion from "Rufus L":
对于我给定的示例,这可行.
For my given example, this works.
var switchValue = 3;
var resultText = switchValue switch
{
var x when (x >= 1 && x <= 3) => "one to three",
4 => "four",
5 => "five",
_ => "unknown",
};
但这并不是我想要完成的.这仍然只是一种情况(具有过滤条件),不会有多个情况产生相同的右手结果.
But it's not exactly what I want to accomplish. This is still only one case (with a filter condition), not multiple cases yielding to the same right-hand result.
推荐答案
我开始安装它,但是我还没有找到使用新语法为单个开关部分指定多个单独的大小写标签的方法.
I got around to installing it, but I have not found a way to specify multiple, separate case labels for a single switch section with the new syntax.
但是,您可以创建一个新变量来捕获该值,然后使用条件表示应该具有相同结果的个案:
However, you can create a new variable that captures the value and then use a condition to represent the cases that should have the same result:
var resultText = switchValue switch
{
var x when
x == 1 ||
x == 2 ||
x == 3 => "one to three",
4 => "four",
5 => "five",
_ => "unknown",
};
如果要测试的案例很多,这实际上会更简洁,因为您可以在一行中测试一系列值:
This is actually more concise if you have many cases to test, because you can test a range of values in one line:
var resultText = switchValue switch
{
var x when x > 0 && x < 4 => "one to three",
4 => "four",
5 => "five",
_ => "unknown",
};
这篇关于C#8开关表达式具有相同结果的多种情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!