我知道这是一个老问题,但在我看来,没有一个答案能给出一个很好的直接原因。
您不需要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