| 財產 | 價值 |
|---|---|
| 規則識別碼 | IDE0306 |
| 職稱 | 使用集合表達式來定義 new |
| 類別 | 風格 |
| 子類別 | 語言規則(語句層級偏好) |
| 適用語言 | C# 12+ |
| 選項 | dotnet_style_prefer_collection_expression |
概觀
此規則標記了可以使用具有展開元素()的..來初始化清單的地方,而不使用new。 例如,該規則提供將程式碼簡化為集合表達式形式的功能,例如 new List<...>(x) 到([.. x])。
選項
選項會指定您希望規則強制執行的行為。 如需設定選項的相關信息,請參閱 選項格式。
dotnet_style_prefer_collection_expression (偏好使用集合表達式的風格)
| 財產 | 價值 | 說明 |
|---|---|---|
| 選項名稱 | dotnet_style_prefer_collection_expression (偏好使用集合表達式的風格) | |
| 選項值 | true | when_types_exactly_match |
只有在類型完全相符時,才偏好使用集合表示式,例如 List<int> list = new List<int>() { 1, 2 };。 |
when_types_loosely_match* |
偏好使用集合表達式,哪怕類型不完全匹配,例如,IEnumerable<int> list = new List<int>() { 1, 2 };。 目標型別必須符合右側的類型,或是下列其中一種類型:IEnumerable<T>、ICollection<T>、IList<T>、IReadOnlyCollection<T>、IReadOnlyList<T>。 |
|
false | never |
停用規則。 | |
| 默認選項值 | when_types_loosely_match* |
*使用此選項時,程式代碼修正可能會變更程式碼的語意。
範例
// Code with violation.
List<int> l1 = new List<int>(Enumerable.Range(1, 10));
List<int> m1 = new List<int>(new[] { 1, 2, 3 });
// Fixed code.
List<int> l1 = [.. Enumerable.Range(1, 10)];
List<int> m1 = [.. new[] { 1, 2, 3 }];
隱藏警告
如果您想要只隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。
#pragma warning disable IDE0306
// The code that's violating the rule is on this line.
#pragma warning restore IDE0306
若要停用檔案、資料夾或項目的規則,請在none中將其嚴重性設為。
[*.{cs,vb}]
dotnet_diagnostic.IDE0306.severity = none
若要停用所有程式碼樣式規則,請將類別 Style 的嚴重性設定為 組態檔中的 none。
[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none
如需詳細資訊,請參閱 如何隱藏程式碼分析警告。