使用模式比對 (IDE0078和 IDE0260)

本文說明兩個相關規則和 IDE0078IDE0260

屬性
規則識別碼 IDE0078
標題 使用模式比對
類別 樣式
子類別 語言規則 (模式比對喜好設定)
適用語言 C# 9.0+
選項 csharp_style_prefer_pattern_matching
屬性
規則識別碼 IDE0260
標題 使用模式比對
類別 樣式
子類別 語言規則 (模式比對喜好設定)
適用語言 C#
選項 csharp_style_pattern_matching_over_as_with_null_check

概觀

此樣式規則涉及使用 C# 模式比對 建構。

IDE0260特別標幟表達式的使用 as ,後面接著讀取 null 條件運算符的成員。 此規則類似於 IDE0019,其會標幟使用 as 表示式, null 後面接著檢查。

選項。

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

csharp_style_prefer_pattern_matching (IDE0078)

屬性 Description
選項名稱 csharp_style_prefer_pattern_matching
選項值 true 盡可能使用模式比對建構
false 不想使用模式比對建構。
默認選項值 true

csharp_style_pattern_matching_over_as_with_null_check (IDE0260)

此選項也會設定規則 IDE0019

屬性 Description
選項名稱 csharp_style_pattern_matching_over_as_with_null_check
選項值 true 偏好使用模式比對表達式與 as Null 條件式成員存取。
false 停用規則。
默認選項值 true

範例

IDE0078

// csharp_style_prefer_pattern_matching = true
var x = i is default(int) or > (default(int));
var y = o is not C c;

// csharp_style_prefer_pattern_matching = false
var x = i == default || i > default(int);
var y = !(o is C c);

IDE0260

// Code with violations.
object? o = null;
if ((o as string)?.Length == 0)
{
}

// Fixed code (csharp_style_pattern_matching_over_as_with_null_check = true).
object? o = null;
if (o is string { Length: 0 })
{
}

隱藏警告

如果您想要只隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

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

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

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

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

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

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

另請參閱