Classe Span2D<T>

La Span2D<T> classe met en miroir les fonctionnalités du Span<T> type, mais prend en charge les régions de mémoire 2D. Comme Memory2D<T>, il est extrêmement flexible et peut encapsuler un certain nombre d’objets différents, ainsi que des pointeurs natifs ou des références GC.

La disposition interne est similaire à la disposition utilisée par le Memory2D<T> type. Il inclut un paramètre de pas qui permet la prise en charge des tampons de mémoire discontiguë. Vous pouvez en savoir plus sur ce sujet dans la Memory2D<T> documentation.

API de plateforme :Span2D<T>, Memory2D<T>, ReadOnlySpan2D<T>

Syntaxe

Voici comment créer une Span2D<T> instance à partir d’un tableau 2D :

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[1, 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 }

Vous pouvez également créer directement une vue 2D sur la mémoire native :

int* p = stackalloc int[9];

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

Le Span2D<T> type inclut des types d’énumérateurs personnalisés pour parcourir facilement une ligne, une colonne ou une zone mémoire entière à l’aide de la syntaxe standard foreach en C#. Il prend également en charge l’exécution d’opérations en bloc dans un seul appel :

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>

Le type ReadOnlySpan2D<T> est au type Span2D<T> ce que ReadOnlySpan<T> est à Span<T>. Il expose un ensemble similaire d’API, mais ne permet pas de modifier directement le contenu de la zone de mémoire sous-jacente.

Exemple de code

Vous trouverez d’autres exemples dans les tests unitaires.