CA1870:使用快取的 'SearchValues' 實例
屬性 | 值 |
---|---|
規則識別碼 | CA1870 |
標題 | 使用快取的 'SearchValues' 實例 |
類別 | 效能 |
修正程式是中斷或非中斷 | 不中斷 |
預設在 .NET 8 中啟用 | 建議 |
原因
IndexOfAny
或 ContainsAny
方法會以許多常數值呼叫,以便改用 。 SearchValues
規則不會標幟使用最多五個值的呼叫,因為這些呼叫已經使用最佳實作。
檔案描述
使用快取 SearchValues<T> 實例比將值傳遞至 IndexOfAny
或 ContainsAny
直接更有效率。
如何修正違規
在欄位中建立 SearchValues<T> 和快取實例,然後將該實例改為傳遞至 IndexOfAny
或 ContainsAny
呼叫。 static readonly
執行此轉換的程式碼修正程式可供使用。
範例
下列程式碼片段顯示 CA1870 的兩個違規:
static readonly char[] MyValues = new[] { 'a', 'b', 'c', 'x', 'y', 'z' };
static int IndexOfMyValues(ReadOnlySpan<char> text)
{
return text.IndexOfAny(MyValues);
}
static bool ContainsOnlyMyValues(ReadOnlySpan<char> text)
{
return !text.ContainsAnyExcept("abcxyz");
}
下列程式碼片段會修正違規:
private static readonly SearchValues<char> s_myValues = SearchValues.Create("abcxyz");
static int IndexOfMyValues(ReadOnlySpan<char> text)
{
return text.IndexOfAny(s_myValues);
}
static bool ContainsOnlyMyValues(ReadOnlySpan<char> text)
{
return !text.ContainsAnyExcept(s_myValues);
}
如果有多個具有相同值集合的呼叫 IndexOfAny
, s_myValues
應該重複使用。
隱藏警告的時機
如果效能不相關,則隱藏此警告是安全的。
隱藏警告
如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。
#pragma warning disable CA1870
// The code that's violating the rule is on this line.
#pragma warning restore CA1870
若要停用檔案、資料夾或專案的規則,請在組態檔 中將其嚴重性設定為 。 none
[*.{cs,vb}]
dotnet_diagnostic.CA1870.severity = none
如需詳細資訊,請參閱 如何隱藏程式碼分析警告 。
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應