ref struct 与栈上高性能数据模式
深入 ref struct 的限制、Span<T> 交互与栈分配优化 · 难度:入门 · +10XP
ref struct 与栈上高性能数据模式
ref struct 是 C# 7.2 引入的特殊值类型,强制实例只能存在于栈上,不能装箱、不能作为类字段、不能用于异步方法。它们与 Span
public ref struct StackBuffer
{
private Span<byte> _span;
public StackBuffer(Span<byte> buffer) => _span = buffer;
public ref byte this[int index] => ref _span[index];
}
// 使用栈分配
Span<byte> stackMem = stackalloc byte[256];
var buf = new StackBuffer(stackMem);
buf[0] = 42;