Repository navigation
ZH TW CSharp Keyword allows
Codex edited this page Oct 11, 2026
·
2 revisions
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
允許引用結構反限制允許您將引用結構作為參數傳遞給泛型類型或方法。它不要求每個參數都是 ref 結構。具有這樣的T的程式碼必須遵循連結安全規則並且不能進行裝箱。反限制寫在其他限制之後。
請將此範例另存為 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
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學習。
ClassicUO — Bad Newbie & C# Scripts IDE