C# 4.0 这一段的这一部分是什么意思?(摘自c#4.0赫伯特·席尔德)

C# 4.0 这一段的这一部分是什么意思?(摘自c#4.0赫伯特·席尔德),c#-4.0,c#-3.0,C# 4.0,C# 3.0,ref和out的使用不限于传递值类型。它们也可以被使用 当传递引用时。ref或out修改引用时,会导致引用, 自身,通过引用传递。这允许方法更改引用的对象 指 这部分是什么意思 ref或out修改引用时,会导致引用, 自身,通过引用传递。这允许方法更改引用的对象 引用。这意味着通过使用ref可以更改变量指向的对象,而不仅仅是对象的内容 假设您有一个带有ref参数的方法,它替换了一个对象: public static void Change(ref StringBuilder str) {

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();
    }
}