簡體   English   中英

為什么 Visual Studio 2019 推薦使用 switch 表達式而不是 switch 語句?

[英]Why does Visual Studio 2019 recommend a switch expression instead of a switch statement?

Visual Studio 2019 建議將我編寫的 switch 語句轉換為switch 表達式(兩者都包含在上下文中)。

對於像這樣的簡單示例,將其編寫為表達式是否有任何技術或性能優勢? 例如,這兩個版本的編譯方式是否不同?

陳述

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

表達

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

在您給出的示例中,實際上並沒有很多。 但是,switch 表達式對於在一個步驟中聲明和初始化變量很有用。 例如:

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

在這里我們可以立即聲明和初始化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");
}

目前 switch 表達式的一個缺點(至少在 VS2019 中)是您不能在單個條件上設置斷點,只能在整個表達式上設置斷點。 但是,使用 switch 語句,您可以在單個 case 語句上設置斷點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM