傳遞實值型別的參數 (C# 程式設計手冊)

實值型別變數直接包含其資料,這點相對於參考型別變數包含其資料的參考。 因此,將一個實值型別變數傳遞到一個方法,意味著將變數的複本傳遞到該方法。 在該方法中對參數的任何變更並不會影響到原本儲存在變數中的資料。 如果想要讓被呼叫之方法變更參數的值,則必須使用 refout 關鍵字,以傳址 (By Reference) 方式傳遞該參數值。 為了簡化,下列範例使用 ref。

範例

下列範例說明以傳值方式傳遞實值型別。 變數 n 是以傳值方式傳遞到方法 SquareIt。 在方法中對參數的任何變更並不會影響到變數原本的值。

class PassingValByVal
{
    static void SquareIt(int x)
    // The parameter x is passed by value.
    // Changes to x will not affect the original value of x.
    {
        x *= x;
        System.Console.WriteLine("The value inside the method: {0}", x);
    }
    static void Main()
    {
        int n = 5;
        System.Console.WriteLine("The value before calling the method: {0}", n);

        SquareIt(n);  // Passing the variable by value.
        System.Console.WriteLine("The value after calling the method: {0}", n);

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    The value before calling the method: 5
    The value inside the method: 25
    The value after calling the method: 5
*/

變數 n 是一個實值型別,包含其資料 5 值。 在叫用 (Invoke) SquareIt 時,n 的內容便會複製到方法括號內的 x 參數。 然而,在 Main 中,呼叫 SquareIt 方法的前後,n 的值是相同的。 事實上,發生在方法內的變更,只會影響區域變數 x。

下列範例除了使用 ref 關鍵字傳遞參數以外,其他部分皆與上一個範例相同。 呼叫方法後參數的值會被變更。

class PassingValByRef
{
    static void SquareIt(ref int x)
    // The parameter x is passed by reference.
    // Changes to x will affect the original value of x.
    {
        x *= x;
        System.Console.WriteLine("The value inside the method: {0}", x);
    }
    static void Main()
    {
        int n = 5;
        System.Console.WriteLine("The value before calling the method: {0}", n);

        SquareIt(ref n);  // Passing the variable by reference.
        System.Console.WriteLine("The value after calling the method: {0}", n);

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    The value before calling the method: 5
    The value inside the method: 25
    The value after calling the method: 25
*/

在本範例中,並非傳遞 n 的值;而是傳遞 n 的參考。 參數 x 不是 int,而是 int 的參考。在此情況下為 n 的參考。 因此,當 x 在方法的括號內時,括號內真正取得的是 x 所參考的 n。

變更傳遞參數常見的範例為 Swap 方法,亦即傳遞兩個參數 x 和 y,並使用此方法交換它們的內容。 您必須以傳址方式將參數傳遞到 Swap 方法,否則,方法內所處理的將為參數的區域複本。 下列為使用參考參數的 Swap 方法範例:

static void SwapByRef(ref int x, ref int y)
{
    int temp = x;
    x = y;
    y = temp;
}

呼叫這個方法時,請使用 ref 關鍵字,如下所示:

static void Main()
{
    int i = 2, j = 3;
    System.Console.WriteLine("i = {0}  j = {1}" , i, j);

    SwapByRef (ref i, ref j);

    System.Console.WriteLine("i = {0}  j = {1}" , i, j);

    // Keep the console window open in debug mode.
    System.Console.WriteLine("Press any key to exit.");
    System.Console.ReadKey();
}
/* Output:
    i = 2  j = 3
    i = 3  j = 2
*/

請參閱

參考

傳遞參數 (C# 程式設計手冊)

傳遞參考型別的參數 (C# 程式設計手冊)

概念

C# 程式設計手冊