[英]Why does a switch-case statement on a string constant require a default in Visual Studio 2019 (prior to 16.0.3) but not in Visual Studio 2017?
[英]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.