Skip to content

KO CSharp Keyword allows

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: allows

핸드북 C# · 실용 가이드

ref struct 제한 제한 허용을 사용하면 ref struct를 제네릭 형식이나 메서드에 대한 인수로 전달할 수 있습니다. 각 인수가 ref 구조체일 필요는 없습니다. 이러한 T가 있는 코드는 링크 안전 규칙을 따라야 하며 복싱을 수행할 수 없습니다. 제한 방지는 다른 제한 사항 뒤에 작성됩니다.

간단한 예제 (Example.cs)

이 예제를 Example.cs로 따로 저장하고 이 페이지의 다른 예제와 독립적으로 실행하세요.

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

결과:

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

결과:

3

Span 및 일반번호에 대한 재설정 기능 1개

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

결과:

Span length: 0; counter: 0

공식 출처: Microsoft 학습.

Clone this wiki locally