共用方式為


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

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

財產 價值
規則標識碼 IDE0029
標題 可以簡化空值檢查(三元條件式檢查)
類別 風格
子類別 語言規則(表達層面偏好)
適用的語言 C# 和 Visual Basic
選項 dotnet_style_coalesce_expression
財產 價值
規則標識碼 IDE0030
標題 空值檢查可以簡化(具可空值的三元條件檢查)
類別 風格
子類別 語言規則(表達層級的偏好設定)
適用的語言 C# 和 Visual Basic
選項 dotnet_style_coalesce_expression
財產 價值
規則標識碼 IDE0270
標題 Null 檢查可以簡化(如果為 Null 檢查)
類別 風格
子類別 語言規則(表達層級的偏好設定)
適用的語言 C# 和 Visual Basic
選項 dotnet_style_coalesce_expression

概述

規則 IDE0029 和 IDE0030 涉及使用 空合運算式,例如,x ?? y,與 三元條件運算式 配合 null 檢查,例如,x != null ? x : y。 規則在表達式的可為空性方面有所不同。

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

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

選項

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

dotnet_style_coalesce_expression

財產 價值 描述
選項名稱 dotnet_style_coalesce_expression
選項值 true 偏好空合併表達式。
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

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

另請參閱