使用條件運算式進行指派 (IDE0045)

屬性
規則識別碼 IDE0045
標題 使用條件運算式進行指派
類別 樣式
子類別 語言規則 (運算式層級喜好設定)
適用語言 C# 和 Visual Basic
引進的版本 Visual Studio 2017
選項 dotnet_style_prefer_conditional_expression_over_assignment

概觀

此樣式規則會決定需要條件式邏輯的指派要使用三元條件運算式還是 if-else 陳述式

選項

選項會指定您想要強制執行規則的行為。 如需設定選項的詳細資訊,請參閱選項格式

dotnet_style_prefer_conditional_expression_over_assignment

屬性 描述
選項名稱 dotnet_style_prefer_conditional_expression_over_assignment
選項值 true 優先使用具有三元條件式的指派
false 優先使用具有 if else 陳述式的指派
預設選項值 true
// dotnet_style_prefer_conditional_expression_over_assignment = true
string s = expr ? "hello" : "world";

// dotnet_style_prefer_conditional_expression_over_assignment = false
string s;
if (expr)
{
    s = "hello";
}
else
{
    s = "world";
}
' dotnet_style_prefer_conditional_expression_over_assignment = true
Dim s As String = If(expr, "hello", "world")

' dotnet_style_prefer_conditional_expression_over_assignment = false
Dim s As String
If expr Then
    s = "hello"
Else
    s = "world"
End If

隱藏警告

若您只想隱藏單一違規,請將前置處理指示詞新增至來源檔案以停用規則,然後重新啟用規則。

#pragma warning disable IDE0045
// The code that's violating the rule is on this line.
#pragma warning restore IDE0045

若要停用檔案、資料夾或專案的規則,請在組態檔中將其嚴重性設定為 none

[*.{cs,vb}]
dotnet_diagnostic.IDE0045.severity = none

若要停用所有程式碼樣式規則,請在組態檔中將類別 Style 的嚴重性設定為 none

[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none

如需詳細資訊,請參閱如何隱藏程式碼分析警告

另請參閱