Skip to content

ES CSharp Keyword allows

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: allows

Manual C# · Guía Práctica

La antirestricción permite ref struct le permite pasar una estructura ref como argumento a un tipo o método genérico. No requiere que cada argumento sea una estructura ref. El código con dicha T debe seguir las reglas de seguridad de enlaces y no puede realizar boxeo. Las antirrestricciones se escriben después de otras restricciones.

Ejemplo sencillo (Example.cs)

Guarde este ejemplo por separado como Example.cs. Ejecútelo independientemente de los demás ejemplos de esta página.

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

Resultado:

2

Sintaxis

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;

Contrato de interfaz para estructura ref sin boxeo.

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

Resultado:

3

Una función de reinicio para Span y número regular

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

Resultado:

Span length: 0; counter: 0

Fuente oficial: Microsoft Aprender.

Clone this wiki locally