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 구문을 사용하여 지정된 행, 열 또는 전체 메모리 영역을 쉽게 트래버스하고 단일 호출에서 대량 작업을 수행하는 사용자 지정 열거자 형식도 포함됩니다.

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> 에 대한 Span2D<T>ReadOnlySpan<T> 값입니다 Span<T>. 유사한 API 집합을 노출하지만 기본 메모리 영역의 내용을 직접 수정할 수 있는 방법은 없습니다.

예제 코드

단위 테스트에서 더 많은 예제를 찾을 수 있습니다.