Repository navigation
IT CSharp Keyword scoped
Codex edited this page Oct 11, 2026
·
2 revisions
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
scoped limita la durata valida di un valore di parametro di riferimento o simile a un riferimento. Il compilatore non consentirà la restituzione di tale riferimento in un modo che superi la durata impostata. Il modificatore non rende i dati immutabili: il ref con ambito consente di modificare il valore del chiamante.
Salvare questo esempio separatamente come Example.cs. Eseguirlo indipendentemente dagli altri esempi di questa pagina.
Example.cs:
// PROJECT-EXAMPLE
void Add(scoped ref int value) { value += 2; }
int count = 3;
Add(ref count);
System.Console.WriteLine(count);Risultato:
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;
}
}Risultato:
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;
}
}Risultato:
20
Fonte ufficiale: Microsoft Impara.
ClassicUO — Bad Newbie & C# Scripts IDE