共用方式為


CA1875:使用 'Regex.Count'

房產 價值觀
規則識別碼 約1875年
標題 使用 Regex.Count
類別 效能
修正是破壞性或非破壞性 Non-breaking
在 .NET 10 中預設啟用 建議

原因

Count from Regex.MatchesMatchCollection屬性用於取得相符項的計數。

規則描述

Regex.CountRegex.Matches(...).Count更簡單、更快速。 該 Count() 方法經過最佳化,可計算匹配項,而無需實現完整的 MatchCollection. 呼叫然後存取.CountMatches()執行不必要的工作,可能會影響效能。

如何修正違規

將對 的 Regex.Matches(...).Count 呼叫取代為 Regex.Count(...)

可以使用自動執行此轉換的 程式碼修正程式

Example

下列程式碼片段顯示 CA1875 的違規情況:

using System.Text.RegularExpressions;

class Example
{
    public int CountWords(string text)
    {
        // Violation
        return Regex.Matches(text, @"\b\w+\b").Count;
    }
}
Imports System.Text.RegularExpressions

Class Example
    Public Function CountWords(text As String) As Integer
        ' Violation
        Return Regex.Matches(text, "\b\w+\b").Count
    End Function
End Class

下列程式碼片段可修正違規:

using System.Text.RegularExpressions;

class Example
{
    public int CountWords(string text)
    {
        // Fixed
        return Regex.Count(text, @"\b\w+\b");
    }
}
Imports System.Text.RegularExpressions

Class Example
    Public Function CountWords(text As String) As Integer
        ' Fixed
        Return Regex.Count(text, "\b\w+\b")
    End Function
End Class

隱藏警告的時機

如果效能不是問題,或者您以不包含 Regex.Count (.NET 7 之前) 的 .NET 版本為目標,則隱藏此規則的警告是安全的。

隱藏警告

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

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

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

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

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

另請參閱