Share via


CA1832:請使用 AsSpan 或 AsMemory 來取得陣列的 ReadOnlySpan 或 ReadOnlyMemory 部分,不要使用範圍型的索引子

屬性
規則識別碼 CA1832
標題 請使用 AsSpan 或 AsMemory 來取得陣列的 ReadOnlySpan 或 ReadOnlyMemory 部分,不要使用範圍型的索引子
類別 效能
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 建議

原因

在陣列上使用範圍索引子,並隱含地將值指派給 ReadOnlySpan<T>ReadOnlyMemory<T> 時。

檔案描述

上的 Span<T> 範圍索引子是非複製 Slice 作業。 但是對於陣列上的範圍索引子,將會使用 方法 GetSubArray ,而不是 Slice ,這會產生陣列所要求部分的複本。 當此複本隱含使用為 ReadOnlySpan<T>ReadOnlyMemory<T> 值時,通常不需要此複本。 如果不是想要複製,請使用 AsSpanAsMemory 方法來避免不必要的複製。 如果複製是想要的,請先將它指派給區域變數,或新增明確的轉換。

只有在範圍索引子作業的結果上使用隱含轉換時,分析器才會報告。

檢測

隱含轉換:

  • ReadOnlySpan<SomeT> slice = arr[a..b];
  • ReadOnlyMemory<SomeT> slice = arr[a..b];

不會偵測

明確轉換:

  • ReadOnlySpan<SomeT> slice = (ReadOnlySpan<SomeT>)arr[a..b];
  • ReadOnlyMemory<SomeT> slice = (ReadOnlyMemory<SomeT>)arr[a..b];

如何修正違規

若要修正此規則的違規,請使用 AsSpanAsMemory 擴充方法來避免建立不必要的資料複本。

class C
{
    public void TestMethod(byte[] arr)
    {
        // The violation occurs for both statements below
        ReadOnlySpan<byte> tmp1 = arr[0..2];
        ReadOnlyMemory<byte> tmp3 = arr[5..8];
        ...
    }
}
class C
{
    public void TestMethod(byte[] arr)
    {
        // The violations fixed with AsSpan or AsMemory accordingly
        ReadOnlySpan<byte> tmp1 = arr.AsSpan()[0..2];
        ReadOnlyMemory<byte> tmp3 = arr.AsMemory()[5..8];
        ...
    }
}

提示

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

Code fix for CA1832 - Use AsSpan or AsMemory instead of Range-based indexers for getting ReadOnlySpan or ReadOnlyMemory portion of an array

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

class C
{
    public void TestMethod(byte[] arr)
    {
        // The violation occurs
        ReadOnlySpan<byte> tmp1 = arr[0..2];
        ReadOnlyMemory<byte> tmp3 = arr[5..8];
        ...
    }
}
class C
{
    public void TestMethod(byte[] arr)
    {
        // The violation fixed with explicit casting
        ReadOnlySpan<byte> tmp1 = (ReadOnlySpan<byte>)arr[0..2];
        ReadOnlyMemory<byte> tmp3 = (ReadOnlyMemory<byte>)arr[5..8];
        ...
    }
}

隱藏警告的時機

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

隱藏警告

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

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

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

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

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

另請參閱