Multi-variable switch statement in C#(C#中的多变量switch语句)
问题描述
我想使用一个带有多个变量的 switch 语句,如下所示:
I would like use a switch statement which takes several variables and looks like this:
switch (intVal1, strVal2, boolVal3)
{
case 1, "hello", false:
break;
case 2, "world", false:
break;
case 2, "hello", false:
etc ....
}
有没有办法在 C# 中做这样的事情?(出于显而易见的原因,我不想使用嵌套的 switch 语句).
Is there any way to do something like this in C#? (I do not want to use nested switch statements for obvious reasons).
.net 开发团队通过实施这种恐惧来回答了这个问题:C#中的多变量switch语句
The question was answered by .net dev team by implementing of exactly this fearture: Multi-variable switch statement in C#
推荐答案
是的.从 .NET 4.7 和 C# 8 开始支持它.语法与您提到的差不多,但带有一些括号(请参阅 元组模式).
Yes. It's supported as of .NET 4.7 and C# 8. The syntax is nearly what you mentioned, but with some parenthesis (see tuple patterns).
switch ((intVal1, strVal2, boolVal3))
{
case (1, "hello", false):
break;
case (2, "world", false):
break;
case (2, "hello", false):
break;
}
如果你想切换并返回一个值,这里有一个切换表达式语法".这是一个例子;注意默认情况下使用 _
:
If you want to switch and return a value there's a switch "expression syntax". Here is an example; note the use of _
for the default case:
string result = (intVal1, strVal2, boolVal3) switch
{
(1, "hello", false) => "Combination1",
(2, "world", false) => "Combination2",
(2, "hello", false) => "Combination3",
_ => "Default"
};
这是上面链接的 MSDN 文章中一个更具说明性的示例(石头、剪刀、石头游戏):
Here is a more illustrative example (a rock, paper, scissors game) from the MSDN article linked above:
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#中的多变量switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#中的多变量switch语句


- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01