为什么不能在 C# 7.2 的结构中同时使用只读缓冲区和固定大小缓冲区

Why is it not possible to use both readonly and fixed-size buffers in structs in C# 7.2

随着 C# 7.2 的发布,现在可以拥有 readonly 结构,这在许多情况下可以提高性能。

对于我的一个结构,我使用固定大小的字节数组来实际保存数据。然而,当我标记 struct 和字节数组字段 readonly 时,C# 编译器抱怨 readonly 在该字段上无效。为什么我不能在 struct 中的字段上同时使用 fixedreadonly

readonly unsafe struct MyStruct {
  readonly fixed byte _Value[6]; //The modifier 'readonly' is not valid for this item.
}

因为 C# 规范是这样说的(而且它一直都是这样,甚至在 c# 7.2 之前也是如此)。在名为“固定大小缓冲区声明”的 18.7.1 部分中,fixed 缓冲区声明允许使用以下修饰符:

new

public

protected

internal

private

unsafe

这里没有readonly。如果您考虑一下 - 它无论如何都没有多大意义,因为固定缓冲区大小由指针表示,并且您不能限制对指针的写访问。例如:

var s = new MyStruct();
byte* value = s._Value;
// how can you prevent writing to `byte*`?