gpt4 book ai didi

c# - C#中的多变量switch语句

转载 作者:IT王子 更新时间:2023-10-29 04:32:43 24 4
gpt4 key购买 nike

我想使用带有多个变量的 switch 语句,如下所示:

switch (intVal1, strVal2, boolVal3)
{
case 1, "hello", false:
break;
case 2, "world", false:
break;
case 2, "hello", false:

etc ....
}

有没有办法在 C# 中做这样的事情? (出于显而易见的原因,我不想使用嵌套的 switch 语句)。

.net 开发团队通过实现这个功能回答了这个问题:Multi-variable switch statement in C#

最佳答案

是的。从 .NET 4.7 和 C# 8 开始支持它。语法几乎与您提到的一样,但带有一些括号(请参阅 tuple patterns)。

switch ((intVal1, strVal2, boolVal3))
{
case (1, "hello", false):
break;
case (2, "world", false):
break;
case (2, "hello", false):
break;
}

如果你想切换并返回一个值,有一个切换“表达式语法”。这是一个例子;注意在默认情况下使用 _:

string result = (intVal1, strVal2, boolVal3) switch
{
(1, "hello", false) => "Combination1",
(2, "world", false) => "Combination2",
(2, "hello", false) => "Combination3",
_ => "Default"
};

下面是上面链接的 MSDN 文章中的一个更具说明性的示例(剪刀石头布游戏):

public static string RockPaperScissors(string first, string second)
=> (first, second) switch
{
("rock", "paper") => "rock is covered by paper. Paper wins.",
("rock", "scissors") => "rock breaks scissors. Rock wins.",
("paper", "rock") => "paper covers rock. Paper wins.",
("paper", "scissors") => "paper is cut by scissors. Scissors wins.",
("scissors", "rock") => "scissors is broken by rock. Rock wins.",
("scissors", "paper") => "scissors cuts paper. Scissors wins.",
(_, _) => "tie"
};

关于c# - C#中的多变量switch语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7967523/

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