Repository navigation
FR CSharp Keyword allows
Codex edited this page Oct 11, 2026
·
2 revisions
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
L’antirestriction makes ref struct vous permet de transmettre une ref struct comme argument à un type ou une méthode générique. Il n’est pas nécessaire que chaque argument soit une structure ref. Le code avec un tel T doit suivre les règles de sécurité des liens et ne peut pas effectuer de boxe. Les anti-restrictions sont écrites après d'autres restrictions.
Enregistrez cet exemple séparément dans Example.cs. Exécutez-le indépendamment des autres exemples de cette page.
Example.cs:
// PROJECT-EXAMPLE
void Ignore<T>(T value) where T : allows ref struct { }
System.Span<int> values = stackalloc int[2];
Ignore(values);
System.Console.WriteLine(values.Length);Résultat:
2
static int Measure<T>(T value) where T : IMeasured, allows ref struct;
static void Reset<T>(scoped ref T value) where T : allows ref struct;using System;
public interface IMeasured { int Length { get; } }
public readonly ref struct NumberView : IMeasured
{
private readonly ReadOnlySpan<int> values;
public NumberView(ReadOnlySpan<int> values) => this.values = values;
public int Length => values.Length;
}
internal static class Program
{
public static void Main()
{
ReadOnlySpan<int> values = stackalloc int[] { 4, 8, 15 };
var view = new NumberView(values);
Console.WriteLine(Measure(view));
}
private static int Measure<T>(T value) where T : IMeasured, allows ref struct
=> value.Length;
}Résultat:
3
using System;
internal static class Program
{
public static void Main()
{
Span<int> scratch = stackalloc int[] { 1, 2, 3 };
int counter = 7;
Reset(ref scratch);
Reset(ref counter);
Console.WriteLine($"Span length: {scratch.Length}; counter: {counter}");
}
private static void Reset<T>(scoped ref T value) where T : allows ref struct
=> value = default!;
}Résultat:
Span length: 0; counter: 0
Source officielle : Microsoft Apprendre.
ClassicUO — Bad Newbie & C# Scripts IDE