使用用于构建器的集合表达式 (IDE0304)

财产
规则 ID IDE0304
标题 使用生成器的集合表达式
类别 样式
子类别 语言规则(表达式级首选项)
适用的语言 C# 12+
选项 dotnet_style_prefer_collection_expression

概述

此规则标记调用 CreateBuilder() 或类似方法的位置,以创建将添加元素并最终构造具有 CollectionBuilderAttribute 属性的集合类型的生成器类型(例如,通过调用 ImmutableArray<T>.Builder.ToImmutable())。 相反,可以使用集合表达式 ([...]) 来初始化集合。

备注

此规则需要更新版本的不可变 API(例如 System.Collections.Immutable,选择加入集合表达式模式)。

选项

选项指定你希望规则强制实施的行为。 若要了解如何配置选项,请参阅选项格式

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.
var builder = ImmutableArray.CreateBuilder<int>();
builder.Add(1);
builder.AddRange(new int[] { 5, 6, 7 });
ImmutableArray<int> i = builder.ToImmutable();

// Fixed code.
ImmutableArray<int> i = [1, .. new int[] { 5, 6, 7 }];

屏蔽警告

如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。

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

若要对文件、文件夹或项目禁用该规则,请在none中将其严重性设置为

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

Style中,要禁用所有代码样式规则,请将类别 none 的严重性设置为

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

有关详细信息,请参阅如何禁止显示代码分析警告

另请参阅