CA1514:避免重複長度引數

屬性
規則識別碼 CA1514
標題 避免備援長度引數
類別 可維護性
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 建議

原因

當分割至字串或緩衝區結尾時,會將備援長度引數傳遞至 String.SubstringSpan<T>.SliceReadOnlySpan<T>.SliceMemory<T>.Slice

檔案描述

明確計算的長度引數可能會容易出錯,而且當您要切割至字串或緩衝區結尾時,並不需要。

省略 length 引數的程式碼更容易閱讀及維護。

如何修正違規

移除 length 引數。

範例

下列程式碼片段顯示 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

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