Skip to content

ZH TW CSharp Keyword allows

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: allows

使用手冊C# · 實用指南

允許引用結構反限制允許您將引用結構作為參數傳遞給泛型類型或方法。它不要求每個參數都是 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;

沒有裝箱的 ref 結構的介面契約

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和常規號碼具有一次清零功能

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