【问题标题】:Defining a variable inside a switch() closure在 switch() 闭包中定义变量
【发布时间】:2017-11-17 14:41:45
【问题描述】:

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

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

   default: break;
}

public static int GetSomeNum() => 3;

【问题讨论】:

标签: c# switch-statement case computer-science var


【解决方案1】:

documentation 这么说

在 C# 6 中,匹配表达式必须是返回 以下类型的值:

  • 一个字符。

  • 一个字符串。

  • 一个布尔值。

  • 整数值,例如 int 或 long。

  • 一个枚举值。

从 C# 7 开始,匹配表达式可以是任何非 null 表达。

回答你的问题,

是的你可以打开一个 int,例如

int myInt = 3;
switch(myInt)

您可以打开返回 it 的方法的结果,例如

int GetMyInt() 
{
    // Get my Int
}

switch(GetMyInt())

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

int GetMyInt() 
{
    // Get my Int
}

int myInt = GetMyInt();

switch(myInt)

你不能那样做。

【讨论】:

  • 谢谢!我之所以问,是因为我看到了关于 c# 7 的 microsoft 主题演讲,但没有正确记住他们介绍的所有新内容,也无法在任何地方找到答案。
猜你喜欢
  • 2012-10-20
  • 2021-08-11
  • 2012-11-03
  • 2017-05-11
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
  • 2019-08-26
相关资源
最近更新 更多