本文說明兩個相關規則,IDE0078
和 IDE0260
。
財產 | 價值 |
---|---|
規則標識碼 | IDE0078 |
標題 | 使用模式比對 |
類別 | 風格 |
子類別 | 語言規則(模式匹配偏好設定) |
適用的語言 | C# 9.0+ |
選項 | csharp_style_prefer_pattern_matching |
財產 | 價值 |
---|---|
規則標識碼 | IDE0260 |
標題 | 使用模式比對 |
類別 | 風格 |
子類別 | 語言規則 (圖樣比對喜好設定) |
適用的語言 | C# |
選項 | csharp_style_pattern_matching_over_as_with_null_check |
概述
此樣式規則涉及使用 C# 中的 模式匹配 結構。
IDE0260特別標記使用 as
表達式,後接透過 空條件運算符的成員讀取。 類似於 IDE0019的這條規則會標示使用 as
表達式,接著進行 null
檢查。
選項
選項會指定您希望規則強制執行的行為。 如需設定選項的相關資訊,請參閱 選項格式。
csharp_style_prefer_pattern_matching (IDE0078)
財產 | 價值 | 描述 |
---|---|---|
選項名稱 | csharp_style_prefer_pattern_matching | |
選項值 | true |
盡可能使用模式比對建構 |
false |
不想使用模式比對建構。 | |
預設選項值 | true |
csharp_style_pattern_matching_over_as_with_null_check (IDE0260)
此選項也會設定 IDE0019規則。
財產 | 價值 | 描述 |
---|---|---|
選項名稱 | csharp_樣式_模式匹配_優於_as_帶空檢查 | |
選項值 | true |
優先使用模式比對,而不是使用具有null條件成員存取的as 表示式。 |
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
如需詳細資訊,請參閱 如何在隱藏程式代碼分析警告。