使用 Create() 的集合表达式 (IDE0303)

属性
规则 ID IDE0303
标题 使用 Create 的集合表达式
类别 Style
Subcategory 语言规则(表达式级首选项)
适用的语言 C# 12+
选项 dotnet_style_prefer_collection_expression

概述

此规则标记使用 Create() 方法或指定为集合构造方法(使用 CollectionBuilderAttribute 属性)的类似方法初始化集合的位置,并建议将其替换为 集合表达式 ([...])。

Create() 方法常用于不可变集合,例如 ImmutableArray.Create(1, 2, 3)

注意

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

选项

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

dotnet_style_prefer_collection_expression

属性 价值 说明
选项名称 dotnet_style_prefer_collection_expression
选项值 true | when_types_exactly_match 只有在类型完全匹配时才首选使用集合表达式,例如 ImmutableArray<int> i = ImmutableArray.Create(1, 2, 3);
when_types_loosely_match
(.NET 9 及更高版本)*
即使在类型属于松散匹配的情况下,也首选使用集合表达式,例如 IEnumerable<int> i = ImmutableArray.Create(1, 2, 3);。 目标类型必须与右侧的类型匹配或者是以下类型之一:IEnumerable<T>ICollection<T>IList<T>IReadOnlyCollection<T>IReadOnlyList<T>
false | never 禁用规则。
默认选项值 .NET 8 中的 true
.NET 9 及更高版本中的 when_types_loosely_match

*使用此选项时进行的代码修复可能会更改代码的语义。

示例

// Code with violations.
ImmutableArray<int> i = ImmutableArray.Create(1, 2, 3);
IEnumerable<int> j = ImmutableArray.Create(1, 2, 3);

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

以下代码片段显示了一个带有 CollectionBuilderAttribute 附注的自定义类型的示例。

public class Program
{
    public static void Main()
    {
        // IDE0303 violation.
        MyCollection<int> c = MyCollection.Create(1, 2, 3);

        // IDE0303 fixed code.
        MyCollection<int> c = [1, 2, 3];
    }
}

static partial class MyCollection
{
    public static MyCollection<T> Create<T>(System.ReadOnlySpan<T> values) => default;
    public static MyCollection<T> Create<T>(T t1, T t2, T t3) => default;
}

[CollectionBuilder(typeof(MyCollection), "Create")]
class MyCollection<T> : IEnumerable<T>
{
    public IEnumerator<T> GetEnumerator() => default;
    IEnumerator IEnumerable.GetEnumerator() => default;
}

抑制警告

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

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

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

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

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

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

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

另请参阅