为什么 Visual Studio 2019 推荐使用 switch 表达式而不是 switch 语句?

AGB*_*AGB 3 c# switch-statement switch-expression

Visual Studio 2019 建议将我编写的 switch 语句转换为 switch表达式(两者都包含在下面用于上下文)。

对于这样的简单示例,将其编写为表达式是否有任何技术或性能优势?例如,这两个版本的编译方式是否不同?

陈述

switch(reason)
{
    case Reasons.Case1: return "string1";
    case Reasons.Case2: return "string2";
    default: throw new ArgumentException("Invalid argument");
}
Run Code Online (Sandbox Code Playgroud)

表达

return reason switch {
    Reasons.Case1 => "string1",
    Reasons.Case2 => "string2",
    _ => throw new ArgumentException("Invalid argument")
};
Run Code Online (Sandbox Code Playgroud)

Sea*_*ean 7

在您提供的示例中,实际上并没有太多内容。然而,switch 表达式对于一步声明和初始化变量很有用。例如:

var description = reason switch 
{
    Reasons.Case1 => "string1",
    Reasons.Case2 => "string2",
    _ => throw new ArgumentException("Invalid argument")
};
Run Code Online (Sandbox Code Playgroud)

在这里我们可以description立即声明和初始化。如果我们使用 switch 语句,我们必须这样说:

string description = null;
switch(reason)
{
    case Reasons.Case1: description = "string1";
                        break;
    case Reasons.Case2: description = "string2";
                        break;
    default:            throw new ArgumentException("Invalid argument");
}
Run Code Online (Sandbox Code Playgroud)

目前 switch 表达式的一个缺点(至少在 VS2019 中)是你不能在单个条件上设置断点,只能在整个表达式上设置断点。但是,使用 switch 语句,您可以在单个 case 语句上设置断点。

  • @Sheradil 无论如何,两个版本都会产生基本相同的 IL,所以我怀疑是否有性能优势。 (4认同)