ref和out的使用不限于传递值类型。它们也可以使用当传递引用时。当ref或out修改引用时,它会导致引用,其本身,以通过引用传递。这允许方法更改引用的对象指
这部分是什么意思?
当ref或out修改引用时,它会导致引用,其本身,以通过引用传递。这允许方法更改引用的对象指.
这意味着通过使用ref
,您可以更改变量指向的对象,而不仅仅是对象的内容。
假设您有一个带有ref
参数的方法,它将替换一个对象:
public static void Change(ref StringBuilder str) {
str.Append("-end-");
str = new StringBuilder();
str.Append("-start-");
}
当你调用它时,它会更改你调用它的变量:
StringBuilder a = new StringBuilder();
StringBuilder b = a; // copy the reference
a.Append("begin");
// variables a and b point to the same object:
Console.WriteLine(a); // "begin"
Console.WriteLine(b); // "begin"
Change(b);
// now the variable b has changed
Console.WriteLine(a); // "begin-end-"
Console.WriteLine(b); // "-start-"
您可以这样做:
MyClass myObject = null;
InitializeIfRequired(ref myObject);
// myObject is initialized
...
private void InitializeIfRequired(ref MyClass referenceToInitialize)
{
if (referenceToInitialize == null)
{
referenceToInitialize = new MyClass();
}
}