為避免 '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_樣式匹配優於使用as和空檢查
此選項也會配置規則 IDE0260。
財產 | 價值 | 描述 |
---|---|---|
選項名稱 | 使用模式匹配來替代使用as和null檢查的C#風格 | |
選項值 | 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
如需詳細資訊,請參閱 如何在隱藏程式代碼分析警告。
另請參閱
- 使用模式比對:IDE0078和IDE0260
- C# 中的 模式比對
- 程式代碼樣式語言規則
- 程式碼樣式規則參考