共用方式為


CA1858:使用 StartsWith 代替 IndexOf

屬性
規則識別碼 CA1858
標題 使用 StartsWith 而非 IndexOf
類別 效能
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 建議

原因

String.IndexOf 會呼叫 ,且其結果會與零進行比較。

檔案描述

呼叫比呼叫 String.StartsWithString.IndexOf 更有效率且更清楚,並且比較結果與零,以判斷字串是否以指定的前置詞開頭。

IndexOf 會搜尋整個字串,而 StartsWith 只會在字串開頭比較。

如何修正違規

將 的呼叫 String.IndexOf 取代為 的 String.StartsWith 呼叫。

範例

下列程式碼片段顯示 CA1858 的違規:

bool M(string s)
{
    return s.IndexOf("abc") == 0;
}
Function M(s As String) As Boolean
    Return s.IndexOf("abc") = 0
End Function

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

bool M(string s)
{
    return s.StartsWith("abc");
}
Function M(s As String) As Boolean
    Return s.StartsWith("abc")
End Function

隱藏警告的時機

如果效能不相關,則隱藏此警告是安全的。

隱藏警告

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

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

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

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

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