| 资产 | 价值 |
|---|---|
| 规则 ID | CA1875 |
| 标题 | 使用 Regex.Count |
| 类别 | 性能 |
| 修复是中断修复还是非中断修复 | Non-breaking |
| 在 .NET 10 中默认启用 | 作为建议 |
原因
From CountRegex.Matches 的属性MatchCollection用于获取匹配项计数。
规则说明
Regex.Count 比 Regex.Matches(...).Count。 该方法 Count() 针对计数匹配项进行优化,而不会具体化完整 MatchCollection。 调用 Matches() 然后访问 .Count 会执行可能影响性能的不必要的工作。
如何修复违规行为
将调用Regex.Matches(...).CountRegex.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
何时禁止显示警告
如果性能不关心或面向不包含 .NET 7 的 .NET 版本(在 .NET Regex.Count 7 之前),则禁止显示此规则的警告是安全的。
禁止显示警告
如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。
#pragma warning disable CA1875
// The code that's violating the rule is on this line.
#pragma warning restore CA1875
若要禁用文件、文件夹或项目的规则,请在none中将其严重性设置为。
[*.{cs,vb}]
dotnet_diagnostic.CA1875.severity = none
有关详细信息,请参阅 如何禁止显示代码分析警告。