Skip to content

IT CSharp Keyword allows

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: allows

Manuale C# · Guida pratica

L'antirestrizione permette ref struct consente di passare una ref struct come argomento a un tipo o metodo generico. Non è necessario che ogni argomento sia una struttura ref. Il codice con tale T deve seguire le regole della sicurezza del collegamento e non può eseguire il boxing. Le anti-restrizioni vengono scritte dopo le altre restrizioni.

Esempio semplice (Example.cs)

Salvare questo esempio separatamente come Example.cs. Eseguirlo indipendentemente dagli altri esempi di questa pagina.

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);

Risultato:

2

Sintassi

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;

Contratto di interfaccia per struttura di ristrutturazione senza boxing

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;
}

Risultato:

3

Una funzione di ripristino per Span e numero normale

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!;
}

Risultato:

Span length: 0; counter: 0

Fonte ufficiale: Microsoft Impara.

Clone this wiki locally