为什么我可以在 c#7.3 中将 ref 结构声明为 class 的成员?

Why can I declare a ref struct as a member of a class in c#7.3?

根据docs

You can't declare a ref struct as a member of a class or a normal struct.

但我设法编译了 运行 这个:

public ref struct RefStruct
{
    public int value;
}
public class MyClass
{
    public RefStruct Item => default;
}    
...       

MyClass c = new MyClass();
Console.WriteLine(c.Item.value);

现在 RefStructref struct 并且是 class 的成员。 这种说法在某些情况下是错误的吗?

更新 现在文档已更新为更准确的描述。

它不是您 class 的字段,而是 属性 getter 的 return 值 - 这很好,因为它只是函数 return值。

请注意 "as a member of a class" 通常包含属性,可能应更改为 "field of a class"。

如果您尝试将其声明为 class 字段(直接或间接通过 auto-implemented 属性),这将需要 class( ref struct) 的数据分配在堆栈上,其余分配在托管堆中。

问题中的代码定义了non-autoimplemented属性。因此,编译器无需在 class 中自动创建 属性 类型的隐藏字段。因此,虽然 属性 结果类型是 ref struct,但它实际上并未存储在 class 中,因此不违反此 ref struct 类型不包含在任何 class 中的要求].请注意,即使制作 setter 方法本身也很好 - 为 属性 存储值会很棘手,但您可以安全地存储 ref struct 的内容(public int value;set 中的 post) 并在 get 中重新创建它。