gpt4 book ai didi

C# 多个开关情况相同的值 lambda 语法

转载 作者:行者123 更新时间:2023-12-03 23:34:26 24 4
gpt4 key购买 nike

可以这样转换:

int x = 1;
string xString;
switch (x)
{
case 1:
xString = "1";
break;
case 2:
xString = "2";
break;
default:
xString = "default";
break;
}
Console.WriteLine(xString);

进入这个:
int x = 1;
string xString = x switch
{
1 => "1",
2 => "2",
_ => "default",
};
Console.WriteLine(xString);

但是,在多个情况下将 xString 的值设置为相同值而不为每种情况创建 lambda 行的语法是什么?
int x = 1;
string xString;
switch (x)
{
case 1:
xString = "1";
break;
case 2:
case 4:
xString = "even numbers";
break;
default:
xString = "default";
break;
}
Console.WriteLine(xString);

最佳答案

不幸的是,您不能使用范围,但您可以使用 when .

str = i switch
{
int n when (n >= 100) => "asd1",
int n when (n < 100 && n >= 50) => "asd2",
int n when (n < 50) => "asd3",
_ => str
};
或丢弃和隐式引用
str = i switch
{
_ when i >= 100 => "asd1",
_ when i < 100 && i >= 50 => "asd2",
_ when i < 50 => "asd3",
_ => str
};
switch (C# reference)

Starting with C# 7.0, because case statements need not be mutuallyexclusive, you can add a when clause to specify an additionalcondition that must be satisfied for the case statement to evaluate totrue. The when clause can be any expression that returns a Booleanvalue.

关于C# 多个开关情况相同的值 lambda 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62445315/

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