Repository navigation
DE CSharp Keyword scoped
Codex edited this page Oct 11, 2026
·
2 revisions
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
Handbuch C# · Praktischer Leitfaden
„scoped“ begrenzt die gültige Lebensdauer einer Referenz oder eines ref-ähnlichen Parameterwerts. Der Compiler lässt nicht zu, dass eine solche Referenz in einer Weise zurückgegeben wird, die die festgelegte Lebensdauer überschreitet. Der Modifikator macht die Daten nicht unveränderlich: Die bereichsbezogene Referenz ermöglicht die Änderung des Werts des Aufrufers.
Speichern Sie dieses Beispiel separat als Example.cs. Führen Sie es unabhängig von den anderen Beispielen dieser Seite aus.
Example.cs:
// PROJECT-EXAMPLE
void Add(scoped ref int value) { value += 2; }
int count = 3;
Add(ref count);
System.Console.WriteLine(count);Ergebnis:
5
static int Sum(scoped ReadOnlySpan<int> values);
static void Add(scoped ref int value, int amount);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;
}
}Ergebnis:
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;
}
}Ergebnis:
20
Offizielle Quelle: Microsoft Learn.
ClassicUO — Bad Newbie & C# Scripts IDE