2012-09-04 86 views
-1

ref和out的使用不限於值類型的傳遞。當參考通過時,它們也可以用於 。當ref或out修改引用時,它會引用引用 本身作爲引用傳遞。這允許一種方法改變引用 引用的對象。這段意思是什麼意思? (來自C#4.0 Herbert Schildt)


這是什麼意思?

當ref或out修改引用時,它會引用引用 本身作爲引用傳遞。這允許一種方法改變引用 引用的對象。

回答

2

這意味着通過使用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-" 
1

你可以這樣做:

MyClass myObject = null; 
InitializeIfRequired(ref myObject); 
// myObject is initialized 
... 

private void InitializeIfRequired(ref MyClass referenceToInitialize) 
{ 
    if (referenceToInitialize == null) 
    { 
     referenceToInitialize = new MyClass(); 
    } 
}