分享方式:


CA2009:請勿對 ImmutableCollection 值呼叫 TolmmutableCollection

屬性
規則識別碼 CA2009
標題 請勿對 ImmutableCollection 值呼叫 TolmmutableCollection
類別 可靠性
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 建議

原因

System.Collections.Immutable 命名空間中不可變的集合上非必要地呼叫 ToImmutable 方法。

檔案描述

System.Collections.Immutable namespace 包含定義不可變集合的類型。 此規則會分析下列不可變的集合類型:

這些類型會定義擴充方法,從現有的 IEnumerable<T> 集合建立新的不可變集合。

這些擴充方法的設計目的是將可變集合轉換成不可變的集合。 不過,呼叫端可能會不小心傳入不可變的集合作為這些方法的輸入。 這代表效能和/或功能問題。

  • 效能問題:不可變集合上的不必要的 Boxing、unboxing 和/或執行時間類型檢查。
  • 潛在的功能問題:當呼叫端實際有不可變的集合時,呼叫端會假設在可變動的集合上運作。

如何修正違規

若要修正違規,請移除不可變集合上的備援 ToImmutable 呼叫。 例如,下列兩個程式碼片段會顯示違反規則,以及如何修正這些程式碼片段:

using System;
using System.Collections.Generic;
using System.Collections.Immutable;

public class C
{
    public void M(IEnumerable<int> collection, ImmutableArray<int> immutableArray)
    {
        // This is fine.
        M2(collection.ToImmutableArray());

        // This leads to CA2009.
        M2(immutableArray.ToImmutableArray());
    }

    private void M2(ImmutableArray<int> immutableArray)
    {
        Console.WriteLine(immutableArray.Length);
    }
}
using System;
using System.Collections.Generic;
using System.Collections.Immutable;

public class C
{
    public void M(IEnumerable<int> collection, ImmutableArray<int> immutableArray)
    {
        // This is fine.
        M2(collection.ToImmutableArray());

        // This is now fine.
        M2(immutableArray);
    }

    private void M2(ImmutableArray<int> immutableArray)
    {
        Console.WriteLine(immutableArray.Length);
    }
}

提示

Visual Studio 中有一個程式碼修正程式碼可供此規則使用。 若要使用它,請將游標放在違規上,然後按 Ctrl + 。 (句號)。 從所呈現的選項清單中,選擇 [移除備援呼叫 ]。

Code fix for CA2009 - Do not call ToImmutableCollection on an ImmutableCollection value

隱藏警告的時機

除非您不擔心不可變集合的不必要配置效能影響,否則請勿隱藏此規則的違規。

隱藏警告

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

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

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

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

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

另請參閱