CA1514:避免冗余长度参数

属性
规则 ID CA1514
标题 避免冗余长度参数
类别 可维护性
修复是中断修复还是非中断修复 非中断
在 .NET 8 中默认启用 作为建议

原因

切片到字符串或缓冲区末尾时,将冗余长度参数传递给 String.SubstringSpan<T>.SliceReadOnlySpan<T>.SliceMemory<T>.Slice

规则说明

显式计算的长度参数可能容易出错,在切片到字符串或缓冲区末尾时不必要。

省略长度参数的代码更易于读取和维护。

如何解决冲突

删除长度参数。

示例

以下代码片段显示了 CA1514 的冲突:

string message = "Hello World!";
string world = message.Substring(6, message.Length - 6); // "World!"
Dim message As String = "Hello World!"
Dim world As String = message.Substring(6, message.Length - 6) ' "World!"

以下代码片段修复了冲突:

string message = "Hello World!";
string world = message.Substring(6); // "World!"
Dim message As String = "Hello World!"
Dim world As String = message.Substring(6) ' "World!"

何时禁止显示警告

如果不在乎代码的可维护性,可安全地禁止显示此规则的冲突。

抑制警告

如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。

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

若要对文件、文件夹或项目禁用该规则,请在配置文件中将其严重性设置为 none

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

有关详细信息,请参阅如何禁止显示代码分析警告