使用集合表示式來處理陣列(IDE0300)
財產 | 價值 |
---|---|
規則標識碼 | IDE0300 |
標題 | 使用集合表達式來操作陣列 |
類別 | 風格 |
子類別 | 語言規則 (表達層級喜好設定) |
適用的語言 | C# 12+ |
選項 | dotnet_style_prefer_collection_expression |
概述
此規則會標示可以使用 集合表示式 來初始化陣列的位置。 例如,此規則提供將程式碼,例如 new C[] { ... }
、new[] { ... }
和 C[] c = { ... }
,簡化為集合表達式的形式([...]
)。
選項
選項會指定您希望規則強制執行的行為。 如需設定選項的相關資訊,請參閱 選項格式。
dotnet_style_prefer_collection_expression
財產 | 價值 | 描述 |
---|---|---|
選項名稱 | dotnet_style_prefer_collection_expression | |
選項值 | true | when_types_exactly_match |
只有在類型完全相符時,偏好使用集合運算式,例如,int[] i = new int[] { 1, 2, 3 }; 。 |
when_types_loosely_match (.NET 9 和更新版本)* |
偏好使用集合表示式,即使類型比較鬆散,例如,IEnumerable<int> i = new int[] { 1, 2, 3 }; 。 目標型別必須符合右側的類型,或是下列其中一種類型:IEnumerable<T>、ICollection<T>、IList<T>、IReadOnlyCollection<T>、IReadOnlyList<T>。 |
|
false | never |
停用規則。 | |
預設選項值 | .NET 8 中的 true .NET 9 和更新版本中的 when_types_loosely_match |
*使用此選項時的程式代碼修正可能會變更程式碼的語意。 例如,如果您擁有 IEnumerable<int> x = new int[] { 1, 2, 3 };
,則在原始程式碼中會產生一個陣列。 但在新的程式代碼中(IEnumerable<int> x = [1, 2, 3];
),會改為產生內部編譯程式合成類型。 如果您使用 is
檢查或轉換,可以觀察此差異。
例
// Code with violations.
int[] i = new int[] { 1, 2, 3 };
IEnumerable<int> j = new int[] { 1, 2, 3 };
// Fixed code.
int[] i = [1, 2, 3];
IEnumerable<int> j = [1, 2, 3];
隱藏警告
如果您想要只隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。
#pragma warning disable IDE0300
// The code that's violating the rule is on this line.
#pragma warning restore IDE0300
若要停用檔案、資料夾或項目的規則,請將其嚴重性設定為 組態檔中的 none
。
[*.{cs,vb}]
dotnet_diagnostic.IDE0300.severity = none
若要停用所有程式碼樣式規則,請將類別 Style
的嚴重性設定為 組態檔中的 none
。
[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none
如需詳細資訊,請參閱 如何在隱藏程式代碼分析警告。