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语句
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01