Skip to content

JA CSharp Keyword scoped

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: scoped

ディレクトリ C# · 実践的な指導

スコープ付きは、参照または参照に似たパラメータ値の有効な有効期間を制限します。コンパイラは、設定された有効期間を超えてそのような参照が返されることを許可しません。修飾子はデータを不変にしません。スコープ付き参照により呼び出し元の値を変更できます。

簡単な例 (Example.cs)

この例を Example.cs として別に保存し、このページの他の例とは独立して実行してください。

Example.cs:

// PROJECT-EXAMPLE
void Add(scoped ref int value) { value += 2; }
int count = 3;
Add(ref count);
System.Console.WriteLine(count);

結果:

5

構文

static int Sum(scoped ReadOnlySpan<int> values);
static void Add(scoped ref int value, int amount);

スコープ付きパラメータの stackalloc からのデータの読み取り

using System;

internal static class Program
{
    public static void Main()
    {
        ReadOnlySpan<int> readings = stackalloc int[] { 3, 5, 7 };
        Console.WriteLine(Sum(readings));
    }
    private static int Sum(scoped ReadOnlySpan<int> values)
    {
        int total = 0;
        foreach (int value in values) total += value;
        return total;
    }
}

結果:

15

参照を返さずにスコープ付き参照を介して数値を変更する

using System;

internal static class Program
{
    public static void Main()
    {
        int points = 10;
        Add(ref points, 4);
        Add(ref points, 6);
        Console.WriteLine(points);
    }
    private static void Add(scoped ref int value, int amount)
    {
        value += amount;
    }
}

結果:

20

公式ソース: Microsoft Learn。

Clone this wiki locally