共用方式為


針對Create()使用集合表達式(IDE0303)

如果“Property”是在非技术背景例如房地产相关,则翻译为“財產”。
規則標識碼 IDE0303
標題 使用集合表達式來建立
類別 樣式
子類別 語言規則 (表達層級偏好)
適用的語言 C# 12+
選項 dotnet_style_prefer_collection_expression

概觀

此規則會標示出使用 Create() 方法或使用 CollectionBuilderAttribute 屬性指定為集合建構方法的類似方法來初始化集合的位置,並建議將其取代為 集合表達式[...])。

Create() 方法對於不可變的集合很常見,例如 ImmutableArray.Create(1, 2, 3)

注意

此規則需要較新版本的不可變 API(例如,System.Collections.Immutable),以選擇加入集合表示式模式。

選項。

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

dotnet_style_prefer_collection_expression (偏好使用集合表達式的風格)

如果“Property”是在非技术背景例如房地产相关,则翻译为“財產”。 描述
選項名稱 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 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

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

另請參閱