我知道,如果我传递一个值类型(int, struct等)作为参数(没有ref关键字),该变量的副本将传递给方法,但如果我使用ref关键字,则传递对该变量的引用,而不是一个新变量。
但是对于引用类型,就像类一样,即使没有ref关键字,也会将引用传递给方法,而不是副本。那么ref关键字与reference-types有什么用呢?
举个例子:
var x = new Foo();
以下两种有什么区别?
void Bar(Foo y) {
y.Name = "2";
}
and
void Bar(ref Foo y) {
y.Name = "2";
}
这里解释得很好:
http://msdn.microsoft.com/en-us/library/s6938f28.aspx
文章摘要:
A variable of a reference type does not contain its data directly; it
contains a reference to its data. When you pass a reference-type
parameter by value, it is possible to change the data pointed to by
the reference, such as the value of a class member. However, you
cannot change the value of the reference itself; that is, you cannot
use the same reference to allocate memory for a new class and have it
persist outside the block. To do that, pass the parameter using the
ref or out keyword.