在 C# 中,既可以通過值也可以通過引用傳遞參數。通過引用傳遞參數允許函數成員(方法、屬性、索引器、運算子和建構函式)更改參數的值,並保持該更改。若要通過引用傳遞參數,請使用 ref 或 out 關鍵字。為簡單起見,本主題的樣本中只使用了 ref 關鍵字。有關 ref 和 out 之間的差異的資訊,請參見、使用 ref 和 out 傳遞數組。
一、值傳遞
實值型別變數直接包含其資料,這與參考型別變數不同,後者包含對其資料的引用。因此,向方法傳遞實值型別變數意味著向方法傳遞變數的一個副本。方法內發生的對參數的更改對該變數中儲存的未經處理資料無任何影響。如果希望所調用的方法更改參數值,必須使用 ref 或 out 關鍵字通過引用傳遞該參數。
為了簡單起見,以下樣本使用 ref。下面的樣本示範通過值傳遞實值型別參數。通過值將變數 myInt 傳遞給方法 SquareIt。方法內發生的任何更改對變數的原始值無任何影響。
// PassingParams1.cs using System;class PassingValByVal...{ static void SquareIt(int x) // The parameter x is passed by value. // Changes to x will not affect the original value of myInt. ...{ x *= x; Console.WriteLine("The value inside the method: {0}", x); } public static void Main() ...{ int myInt = 5; Console.WriteLine("The value before calling the method: {0}", myInt); SquareIt(myInt); // Passing myInt by value. Console.WriteLine("The value after calling the method: {0}", myInt); }}
輸出
The value before calling the method: 5
The value inside the method: 25
The value after calling the method: 5
代碼討論
變數 myInt 為實值型別,包含其資料(值 5)。當調用 SquareIt 時,myInt 的內容被複製到參數 x 中,在方法內將該參數求平方。但在 Main 中,myInt 的值在調用 SquareIt 方法之前和之後是相同的。實際上,方法內發生的更改隻影響局部變數 x。 二、引用傳遞
下面的樣本除使用 ref 關鍵字傳遞參數以外,其餘與“樣本 1”相同。參數的值在調用方法後發生更改
// PassingParams2.cs using System;class PassingValByRef...{ static void SquareIt(ref int x) // The parameter x is passed by reference. // Changes to x will affect the original value of myInt. ...{ x *= x; Console.WriteLine("The value inside the method: {0}", x); } public static void Main() ...{ int myInt = 5; Console.WriteLine("The value before calling the method: {0}", myInt); SquareIt(ref myInt); // Passing myInt by reference. Console.WriteLine("The value after calling the method: {0}", myInt); }}
輸出
The value before calling the method: 5
The value inside the method: 25
The value after calling the method: 25
代碼討論
本樣本中,傳遞的不是 myInt 的值,而是對 myInt 的引用。參數 x 不是 int 類型,它是對 int 的引用(本例中為對 myInt 的引用)。因此,當在方法內對 x 求平方時,實際被求平方的是 x 所引用的項:myInt。