分享方式:


使用 fluent 的集合表示式 (IDE0305)

屬性
規則識別碼 IDE0305
標題 使用集合表達式進行 Fluent
類別 樣式
子類別 語言規則 (運算式層級喜好設定)
適用語言 C# 12+
選項 dotnet_style_prefer_collection_expression

概觀

此規則旗標會以 Fluent 方式建置集合的位置,也就是 、、、 AsSpan()ToList()ToArray()Add()AddRange()方法的鏈結位置。 相反地, 可以使用集合運算式 來初始化集合。 例如,將 x.AddRange(y).Add(z).AsSpan() 轉換成 [x, ..y, z]

選項。

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

dotnet_style_prefer_collection_expression

屬性 數值 Description
選項名稱 dotnet_style_prefer_collection_expression
選項值 true | when_types_exactly_match 只有在類型完全相符時,才偏好使用集合表示式,例如 List<int> list = new[] { 1, 2, 3 }.ToList();
when_types_loosely_match
(.NET 9 和更新版本)*
偏好使用集合表示式,即使類型比對鬆散,例如 IEnumerable<int> list = new[] { 1, 2, 3 }.ToList();。 目標型別必須符合右側的類型,或是下列其中一種類型:IEnumerable<T>、、ICollection<T>IList<T>IReadOnlyCollection<T>IReadOnlyList<T>、 。
false | never 停用規則。
默認選項值 true 在 .NET 8 中
when_types_loosely_match 在 .NET 9 和更新版本中

*使用此選項時的程式代碼修正可能會變更程式碼的語意。

範例

// Code with violation.
List<int> i = new[] { 1, 2, 3 }.ToList();
IEnumerable<int> j = new[] { 1, 2, 3 }.ToList();

// Fixed code.
List<int> i = [1, 2, 3];
IEnumerable<int> j = [1, 2, 3];

隱藏警告

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

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

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

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

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

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

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

另請參閱