C#中的多变量switch语句

Multi-variable switch statement in C#(C#中的多变量switch语句)

本文介绍了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语句

基础教程推荐