ReadOnlySpan<T>.GetPinnableReference Método

Definición

Devuelve una referencia de solo lectura a un objeto de tipo T que se puede usar para anclar.

Este método está diseñado para admitir compiladores de .NET y no está diseñado para que el código de usuario lo llame.

C#
public ref readonly T GetPinnableReference();

Devoluciones

T

Referencia al elemento del intervalo en el índice 0 o null si el intervalo está vacío.

Ejemplos

En el ejemplo siguiente se muestra cómo crear una matriz de enteros, anclarla y escribir cada elemento en la consola.

C#
using System;

// Note: you must compile this sample using the unsafe flag.
// From the command line, type the following: csc sample.cs /unsafe

public class Example
{
    public static unsafe void Main()
    {
        int[] array = CreateInt32Array();

        // Create a span, pin it, and print its elements.
        Span<int> span = array.AsSpan();
        fixed (int* spanPtr = span)
        {
            Console.WriteLine($"Span contains {span.Length} elements:");
            for (int i = 0; i < span.Length; i++)
            {
                Console.WriteLine(spanPtr[i]);
            }
            Console.WriteLine();
        }

        // Create a read-only span, pin it, and print its elements.
        ReadOnlySpan<int> readonlyspan = array.AsSpan();
        fixed (int* readonlyspanPtr = readonlyspan)
        {
            Console.WriteLine($"ReadOnlySpan contains {readonlyspan.Length} elements:");
            for (int i = 0; i < readonlyspan.Length; i++)
            {
                Console.WriteLine(readonlyspanPtr[i]);
            }
            Console.WriteLine();
        }
    }

    private static int[] CreateInt32Array()
    {
        return new int[] { 100, 200, 300, 400, 500 };
    }
}

// The example displays the following output:
//       Span contains 5 elements:
//       100
//       200
//       300
//       400
//       500
//
//       ReadOnlySpan contains 5 elements:
//       100
//       200
//       300
//       400
//       500

Comentarios

Las aplicaciones no deben llamar directamente a GetPinnableReference. En su lugar, los autores de llamadas deben usar la sintaxis normal de anclaje de su lenguaje, como la instrucción fixed de C#.

Si ancla un , no se supone que el resultante es nulo. Este comportamiento es diferente de anclar un string, donde se garantiza que el char* resultante esté terminado en null.

Se aplica a

Producto Versiones
.NET Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Standard 2.0 (package-provided), 2.1