通过引用传递结构时 C# 框或副本?

C# box or copy when passing structs by reference?

c# 是否在此处框住结构?

struct S { int x; }

void foo(ref S s) { s.x = 1; }

main { 
  var s = new S();
  foo(ref s); <-- boxing??
}

我在 类 中听说过有关结构的奇怪内容。这里有拳击吗?这是传会员的副本吗?

class C { S s; }

main { 
  var c = new C();
  foo(ref c.s); <-- boxing here?? copy here???
}
void foo(ref S s) { s.x = 1; }

所以如果你阅读 ref

的文档,Struct 是值类型

Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is NO boxing of a value type when it is passed by reference.

ref (C# Reference)

这里解释 ref 到底在做什么。

The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the called method is reflected in the calling method.