英語で読む

次の方法で共有


ReadOnlySpan<T>.GetPinnableReference メソッド

定義

ピン留めに使用できる T 型のオブジェクトへの読み取り専用参照を返します。

このメソッドは.NET コンパイラをサポートすることを目的としており、ユーザー コードによって呼び出されるものではありません。

C#
public ref readonly T GetPinnableReference();

戻り値

T

インデックス 0 にあるスパンの要素への参照。スパンが空の場合は null

次の例では、整数配列を作成してピン留めし、各要素をコンソールに書き込む方法を示します。

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

注釈

アプリケーションは GetPinnableReferenceを直接呼び出すべきではありません。 代わりに、呼び出し元は、C# の fixed ステートメントなど、言語の通常のピン留め構文を使用する必要があります。

ReadOnlySpan<char>をピン留めした場合、結果の char*は null で終了 と見なされません。 この動作は、結果の char* が null で終了することが保証される stringのピン留めとは異なります。

適用対象

製品 バージョン
.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