使用模式比對避免 'as' 後面接著 'null' 檢查 (IDE0019)

屬性
規則識別碼 IDE0019
標題 使用模式比對避免 as 後面接著 null 檢查
類別 樣式
子類別 語言規則 (模式比對喜好設定)
適用語言 C#
選項 csharp_style_pattern_matching_over_as_with_null_check

概觀

此樣式規則與使用 C# 模式比對而不是 as 運算式後面接著 null 檢查有關。 此規則類似于 IDE0260,它會標示運算式的使用 as ,後面接著透過 Null 條件運算子讀取的成員。

選項

此規則的相關選項會指定偏好使用模式比對還是具有 Null 檢查的 as 運算式,來判斷某個項目是否屬於特定類型。

如需設定選項的詳細資訊,請參閱選項格式

csharp_style_pattern_matching_over_as_with_null_check

此選項也會設定規則 IDE0260

屬性 描述
選項名稱 csharp_style_pattern_matching_over_as_with_null_check
選項值 true 偏好使用模式比對,來判斷某個項目是否屬於特定類型
false 偏好使用具有 Null 檢查的 as 運算式,來判斷某個項目是否屬於特定類型
預設選項值 true
// csharp_style_pattern_matching_over_as_with_null_check = true
if (o is string s) {...}

// csharp_style_pattern_matching_over_as_with_null_check = false
var s = o as string;
if (s != null) {...}

隱藏警告

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

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

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

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

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

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

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

另請參閱