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语句
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
