您可以在 IDE0029、IDE0030 和 IDE0270) (簡化 Null 檢查

本文說明三個相關規則: IDE0029IDE0030IDE0270

屬性
規則識別碼 IDE0029
標題 Null 檢查可以簡化 (三元條件式檢查)
類別 樣式
子類別 語言規則 (運算式層級喜好設定)
適用語言 C# 和 Visual Basic
選項 dotnet_style_coalesce_expression
屬性
規則識別碼 IDE0030
標題 Null 檢查可以簡化 (可為 Null 的三元條件式檢查)
類別 樣式
子類別 語言規則 (運算式層級喜好設定)
適用語言 C# 和 Visual Basic
選項 dotnet_style_coalesce_expression
屬性
規則識別碼 IDE0270
標題 如果 null 檢查) ,則可以簡化 (Null 檢查
類別 樣式
子類別 語言規則 (運算式層級喜好設定)
適用語言 C# 和 Visual Basic
選項 dotnet_style_coalesce_expression

概觀

規則 IDE0029 和 IDE0030 牽涉到使用 Null 聯合運算式,例如 , x ?? y 與具有 null 檢查的三元條件運算式相比較,例如 x != null ? x : y 。 這些規則與運算式的 Null 屬性不同:

  • IDE0029:涉及不可為 Null 的運算式時使用。 例如,xy 是不可為 Null 的參考型別時,此規則可能會建議 x ?? y,而不是 x != null ? x : y
  • IDE0030:涉及可為 Null 的運算式時使用。 例如,xy可為 Null 實值型別可為 Null 參考型別時,此規則可能會建議 x ?? y,而不是 x != null ? x : y

規則 IDE0270 會標幟使用 null 檢查 (== nullis null) ,而不是 使用 null 聯合運算子 (??) 。

選項

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

dotnet_style_coalesce_expression

屬性 描述
選項名稱 dotnet_style_coalesce_expression
選項值 true 偏好 Null 聯合運算式。
false 停用規則。
預設選項值 true

範例

IDE0029 和 IDE0030

// Code with violation.
var v = x != null ? x : y; // or
var v = x == null ? y : x;

// Fixed code.
var v = x ?? y;
' Code with violation.
Dim v = If(x Is Nothing, y, x) ' or
Dim v = If(x IsNot Nothing, x, y)

' Fixed code.
Dim v = If(x, y)

IDE0270

// Code with violation.
class C
{
    void M()
    {
        var item = FindItem() as C;
        if (item == null)
            throw new System.InvalidOperationException();
    }

    object? FindItem() => null;
}

// Fixed code (dotnet_style_coalesce_expression = true).
class C
{
    void M()
    {
        var item = FindItem() as C ?? throw new System.InvalidOperationException();
    }

    object? FindItem() => null;
}
' Code with violation.
Public Class C
    Sub M()
        Dim item = TryCast(FindItem(), C)
        If item Is Nothing Then
            item = New C()
        End If
    End Sub

    Function FindItem() As Object
        Return Nothing
    End Function
End Class

' Fixed code (dotnet_style_coalesce_expression = true).
Public Class C
    Sub M()
        Dim item = If(TryCast(FindItem(), C), New C())
    End Sub

    Function FindItem() As Object
        Return Nothing
    End Function
End Class

隱藏警告

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

#pragma warning disable IDE0029 // Or IDE0030 or IDE0270
// The code that's violating the rule is on this line.
#pragma warning restore IDE0029 // Or IDE0030 or IDE0270

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

[*.{cs,vb}]
dotnet_diagnostic.IDE0029.severity = none
dotnet_diagnostic.IDE0030.severity = none
dotnet_diagnostic.IDE0270.severity = none

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

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

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

另請參閱