共用方式為


CA1829:請使用 Length/Count 屬性,不要使用 Enumerable.Count 方法

屬性
規則識別碼 CA1829
標題 請使用 Length/Count 屬性,不要使用 Enumerable.Count 方法
類別 效能
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 建議

原因

CountLINQ 方法用於支援對等、更有效率 LengthCount 屬性的類型上。

檔案描述

此規則會 Count 針對具有對等但更有效率 LengthCount 屬性的型別集合呼叫 LINQ 方法呼叫,以擷取相同的資料。 LengthCount 屬性不會列舉集合,因此更有效率。

此規則旗標會 Count 呼叫下列具有 Length 屬性的集合類型:

此規則旗標會 Count 使用 Count 屬性呼叫下列集合類型:

分析的集合類型可能會在未來擴充,以涵蓋更多案例。

如何修正違規

若要修正違規,請使用 或 Count 屬性存取取代 Count 方法呼叫 Length 。 例如,下列兩個程式碼片段會顯示違反規則,以及如何修正它:

using System.Collections.Generic;
using System.Linq;

class C
{
    public int GetCount(int[] array)
        => array.Count();

    public int GetCount(ICollection<int> collection)
        => collection.Count();
}
using System.Collections.Generic;

class C
{
    public int GetCount(int[] array)
        => array.Length;

    public int GetCount(ICollection<int> collection)
        => collection.Count;
}

提示

Visual Studio 中有一個程式碼修正程式碼可供此規則使用。 若要使用它,請將游標放在違規上,然後按 Ctrl + 。 (句號)。 從顯示的選項清單中選擇 [使用長度/計數] 屬性,而不是 Count()。

Code fix for CA1829 - Use Length/Count property instead of Count() when available

隱藏警告的時機

如果您不擔心不必要集合列舉對計算計數的效能影響,則隱藏此規則的違規是安全的。

隱藏警告

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

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

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

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

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

另請參閱