[英]Defining a variable inside a switch() closure
Is it possible in C# to define a variable like so? 在C#中是否可以像这样定义变量?
switch(var num = getSomeNum()) {
case 1: //Do something with num
break;
default: break;
}
public static int GetSomeNum() => 3;
The documentation says that 该文件说
In C# 6, the match expression must be an expression that returns a value of the following types: 在C#6中,match表达式必须是一个返回以下类型值的表达式:
a char. 一个字符。
a string. 一个字符串。
a bool. 布尔。
an integral value, such as an int or a long. 整数值,例如int或long。
an enum value. 枚举值。
Starting with C# 7, the match expression can be any non-null expression. 从C#7开始,match表达式可以是任何非null表达式。
To answer your question, 为了回答您的问题,
Yes you can switch on an int, eg 是的,您可以打开一个整数,例如
int myInt = 3;
switch(myInt)
Yes you can switch on the result of a method that returns an it, eg 是的,您可以打开返回它的方法的结果,例如
int GetMyInt()
{
// Get my Int
}
switch(GetMyInt())
Yes you can switch on variable populated with a method result, eg 是的,您可以打开由方法结果填充的变量,例如
int GetMyInt()
{
// Get my Int
}
int myInt = GetMyInt();
switch(myInt)
No you can't do it like that. 不,你不能那样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.