Share via


Span2D<T>

Span2D<T>Span<T> の機能を反映する型ですが、2D メモリのリージョンをサポートしています。 Memory2D<T> と同様、これは非常に柔軟であり、ネイティブ ポインターや GC 参照だけでなく、多種類のオブジェクトをラップできます。

この内部レイアウトは、非連続メモリ バッファーのサポートを可能にするために使用されるピッチ パラメーターなど、Memory2D<T> 型で使用されるレイアウトと似ています。 詳細情報については、 Memory2D<T> のドキュメントをご覧ください。

プラットフォーム API:Span2D<T>Memory2D<T>ReadOnlySpan2D<T>

構文

2D 配列から Span2D<T> インスタンスを作成する方法を次に示します。

int[,] array =
{
    { 1, 2, 3 },
    { 4, 5, 6 }
};

Span2D<int> span = array;

// The memory directly maps the 2*3 array here

span[0, 0] = 10;
span[2, 1] = 20;

// The array is now:
// { 10, 2, 3 },
// { 4, 20, 6 }

// We can also use indices, on supported runtimes
int x = span[0, ^1];

// We can also get references to items, like with arrays
ref int reference = ref span[1, 1];

Span2D<int> slice = span.Slice(0, 1, 2, 2);

// Or alternatively, on supported runtimes

slice = span[.., 1..];

int[,] copy = slice.ToArray();

// The resulting array is:
// { 2, 3 },
// { 20, 6 }

ネイティブ メモリに対して 2D ビューを直接作成することもできます。

int* p = stackalloc int[9];

Span2D<int> span = new Span2D<int>(p, 3, 3);

また、この Span2D<T> 型にはカスタム列挙型が含まれており、C# の標準の foreach 構文を使用して特定の行、列、またはメモリ領域全体を簡単に走査したり、1 回の呼び出しで一括操作を実行したりできます。

int[,] array =
{
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

Span2D<int> span = array;

foreach (int i in span.GetColumn(1))
{
    // 2, 5, 8
}

// We can also iterate by reference
foreach (ref int i in span.GetRow(2))
{
    // 7, 8, 9
}

foreach (int i in span)
{
    // 1, 2, 3, 4, 5...
}

// Set all items in a column to 0
span.GetColumn(0).Clear();

// Set the value of all items in a row
span.GetRow(1).Fill(42);

Span<int> copy = stackalloc int[3];

// Copy all items from a column
span.GetColumn(2).CopyTo(copy);

// Get a copy of a row as an array
int[] array = span.GetRow(1).ToArray();

ReadOnlySpan2D<T>

ReadOnlySpan2D<T> は、ReadOnlySpan<T>Span<T> で何である Span2D<T> 型に対応します。 これは、同様の API のセットを公開しますが、基盤となるメモリ領域の内容を直接変更する方法は提供しません。

サンプル コード

単体テストでは、さらに他の例をご覧になれます。