財產 | 價值 |
---|---|
規則標識碼 | IDE0028 |
標題 | 使用集合初始化器 |
類別 | 風格 |
子類別 | 語言規則(語言表達層級偏好) |
適用的語言 | C# 和 Visual Basic |
選項 | dotnet_style_collection_initializer |
dotnet_style_prefer_collection_expression |
概述
此樣式規則涉及使用 集合初始化表達式,而且如果您使用 C# 12 或更新版本,集合表達式 進行集合初始化。
在 .NET 8 (C# 12) 和更新版本中,如果您已將 dotnet_style_prefer_collection_expression
選項設定為 true
,則 Visual Studio 中的 程式代碼修正 會將集合初始化程式代碼轉換為使用集合表達式 (List<int> list = [1, 2, 3];
)。 在 Visual Basic 和 .NET 7(C# 11)和更早版本中,程式碼修正將程式碼轉為使用集合初始化器(List<int> list = new List<int> { 1, 2, 3 };
)。
注意
如果您在 Visual Studio 中使用 程式代碼修正,在某些情況下,它所提供的變更可能會有不同的語意。 例如,int[] x = new int[] { }
會被替換成 int[] x = [];
,其語意稍有不同——編譯器會使用 x
單例模式,而不是建立新的實例。
選項
設定此規則相關聯選項的值,以指定在初始化集合時,是否偏好使用集合初始化器和集合運算式。
如需設定選項的詳細資訊,請參閱
dotnet_style_collection_initializer
財產 | 價值 | 描述 |
---|---|---|
選項名稱 | dotnet_style_collection_initializer | |
選項值 | true |
偏好使用集合初始化器。 |
false |
不要偏好集合初始化表達式。 | |
預設選項值 | true |
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 * |
*使用此選項時,程式代碼修正可能會變更程式碼的語意。
(此選項僅適用於 C#。
例子
// IDE0028 violation.
List<int> list = new List<int>() { 1, 2, 3 };
// Fixed code (with dotnet_style_prefer_collection_expression = true)
List<int> list = [1, 2, 3];
' IDE0028 violation.
Dim list = New List(Of Integer)
list.Add(1)
list.Add(2)
list.Add(3)
' Fixed code.
Dim list = New List(Of Integer) From {1, 2, 3}
隱藏警告
如果您想要只隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。
#pragma warning disable IDE0028
// The code that's violating the rule is on this line.
#pragma warning restore IDE0028
若要停用檔案、資料夾或項目的規則,請將其嚴重性設定為 組態檔中的 none
。
[*.{cs,vb}]
dotnet_diagnostic.IDE0028.severity = none
若要停用所有程式碼樣式規則,請將類別 Style
的嚴重性設定為 組態檔中的 none
。
[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none
如需詳細資訊,請參閱 如何隱藏程式代碼分析警告。