在 switch() 闭包中定义一个变量

Defining a variable inside a switch() closure

在 C# 中可以这样定义变量吗?

switch(var num = getSomeNum()) {
   case 1: //Do something with num
           break;

   default: break;
}

public static int GetSomeNum() => 3;

documentation 表示

In C# 6, the match expression must be an expression that returns a value of the following types:

  • a char.

  • a string.

  • a bool.

  • an integral value, such as an int or a long.

  • an enum value.

Starting with C# 7, the match expression can be any non-null expression.

为了回答你的问题,

你可以打开一个int,例如

int myInt = 3;
switch(myInt)

是的 你可以打开returns 一个方法的结果,例如

int GetMyInt() 
{
    // Get my Int
}

switch(GetMyInt())

您可以打开用方法结果填充的变量,例如

int GetMyInt() 
{
    // Get my Int
}

int myInt = GetMyInt();

switch(myInt)

你不能那样做。