我知道这是一个老问题,但在我看来,没有一个答案能直接说明原因。
在这种情况下,您不需要使用 ref,原因如下。考虑这个函数:
void Foo(MyClass a1, ref MyClass a2, out MyClass b1, int c1, MyStruct d1, ref MyStruct d2)
{
}
现在调用这个函数
MyClass a = new MyClass();
MyClass b = null
int c = 3;
MyStruct d = new MyStruct();
Foo(a, ref a, b, c, d, ref d);
这是你在函数内部得到的:
void Foo(MyClass a1, ref MyClass a2,
out MyClass b1,
int c1,
MyStruct d1, ref MyStruct d2)
{
a1 is a copy in memory of the pointer to the instantiated class a;
a2 is the pointer to the instantiated class a;
b1 is the pointer to b, but has the additional check of having to be set within this function - and cannot be used before being set;
c1 is a copy in memory of the variable c;
d1 is a copy in memory of the struct d;
d2 is the struct d;
}
要实现的重要事项:
- 将
a1 设置为null 将不会将a 设置为null。
- 将
a2 设置为null 会将a 设置为null。
- 需要设置
b1。
- 设置
c1 将不会更改c。
- 设置
d1 将不会更改d。
- 设置
d2 将更改d。
这允许一些像这样的怪异:
void Foo(MyClass x, ref MyClass y)
{
x = null;
y.Bar("hi");
}
调用如下:
MyClass a = new MyClass();
Foo(a, ref a);
您正在使用一个类,因此您的情况更像是函数调用中的变量a1。这意味着 ref 不是严格要求的。
Jon Skeet 文章对您的帮助不大,因为他的 IntHolder 示例是 struct 而不是 class。 Struct 是类似于 int 的值类型,必须以相同的方式处理。