CA1831:在適用情況下,請使用 AsSpan 做為字串,不要使用範圍型的索引子

屬性
規則識別碼 CA1831
標題 在適用情況下,請使用 AsSpan 做為字串,不要使用範圍型的索引子
類別 效能
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 作為警告

原因

範圍索引子用於字串,且值會隱含指派給 ReadOnlySpan<char>

檔案描述

當您在字串上使用範圍索引子並將它指派給範圍類型時,就會引發此規則。 上的 Span<T> 範圍索引子是非複製 Slice 作業,但對於字串上的範圍索引子,將會使用 方法 Substring ,而不是 Slice 。 這會產生字串所要求部分的複本。 當此複本隱含使用為 ReadOnlySpan<T>ReadOnlyMemory<T> 值時,通常不需要此複本。 如果複製並非預期,請使用 AsSpan 方法來避免不必要的複製。 如果複製是想要的,請先將它指派給區域變數,或新增明確的轉換。 只有在範圍索引子作業的結果上使用隱含轉換時,分析器才會報告。

檢測

隱含轉換:

ReadOnlySpan<char> slice = str[a..b];

不會偵測

明確轉換:

ReadOnlySpan<char> slice = (ReadOnlySpan<char>)str[a..b];

如何修正違規

若要修正此規則的違規,請使用 AsSpan 字串上的 索引子,而不是 Range 以索引子為基礎,以避免建立不必要的資料複本。

public void TestMethod(string str)
{
    // The violation occurs
    ReadOnlySpan<char> slice = str[1..3];
    ...
}
public void TestMethod(string str)
{
    // The violation fixed with AsSpan extension method
    ReadOnlySpan<char> slice = str.AsSpan()[1..3];
    ...
}

提示

Visual Studio 中有一個程式碼修正程式碼可供此規則使用。 若要使用它,請將游標放在違規上,然後按 Ctrl + 。 (句號)。 從所呈現的選項清單中,選擇 [使用 AsSpan] 而不是以 Range 為基礎的索引子。

Code fix for CA1831 - Use AsSpan instead of Range-based indexers when appropriate

您也可以新增明確的轉換,以避免出現這個警告。

public void TestMethod(string str)
{
    // The violation occurs.
    ReadOnlySpan<char> slice = str[1..3];
    ...
}
public void TestMethod(string str)
{
    // The violation avoided with explicit casting.
    ReadOnlySpan<char> slice = (ReadOnlySpan<char>)str[1..3];
    ...
}

隱藏警告的時機

如果想要建立複本,則隱藏違反此規則是安全的。

隱藏警告

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

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

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

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

若要停用此整個規則類別,請將組態檔中類別的嚴重性設定為 none

[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Performance.severity = none

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

另請參閱