使用 ref 和 out 傳遞陣列 (C# 程式設計手冊)

如同所有的 out 參數,陣列型別的 out 參數必須先指派才能使用,也就是說,它必須由被呼叫端指派。 例如:

static void TestMethod1(out int[] arr)
{
    arr = new int[10];   // definite assignment of arr
}

如同所有的 ref 參數,陣列型別的 ref 參數也必須由呼叫端明確指派。 因此就不需要由被呼叫端明確指派。 陣列型別的 ref 參數可以變更為呼叫的結果。 例如,您可以將 null 值指派給陣列或將陣列初始化為不同的陣列。 例如:

static void TestMethod2(ref int[] arr)
{
    arr = new int[10];   // arr initialized to a different array
}

下列兩個範例說明當使用 out 和 ref 將陣列傳遞至方法時,兩者之間的差異。

範例

在以下範例中,theArray 陣列是在呼叫端 (Main 方法) 宣告並在 FillArray 方法中進行初始化。 接著會將陣列元素傳回呼叫端並顯示。

class TestOut
{
    static void FillArray(out int[] arr)
    {
        // Initialize the array:
        arr = new int[5] { 1, 2, 3, 4, 5 };
    }

    static void Main()
    {
        int[] theArray; // Initialization is not required

        // Pass the array to the callee using out:
        FillArray(out theArray);

        // Display the array elements:
        System.Console.WriteLine("Array elements are:");
        for (int i = 0; i < theArray.Length; i++)
        {
            System.Console.Write(theArray[i] + " ");
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Array elements are:
        1 2 3 4 5        
    */

在以下範例中,theArray 陣列是在呼叫端 (Main 方法) 進行初始化並使用 ref 參數來將其傳遞至 FillArray 方法。 有些陣列元素會在 FillArray 方法進行更新。 接著會將陣列元素傳回呼叫端並顯示。

class TestRef
{
    static void FillArray(ref int[] arr)
    {
        // Create the array on demand:
        if (arr == null)
        {
            arr = new int[10];
        }
        // Fill the array:
        arr[0] = 1111;
        arr[4] = 5555;
    }

    static void Main()
    {
        // Initialize the array:
        int[] theArray = { 1, 2, 3, 4, 5 };

        // Pass the array using ref:
        FillArray(ref theArray);

        // Display the updated array:
        System.Console.WriteLine("Array elements are:");
        for (int i = 0; i < theArray.Length; i++)
        {
            System.Console.Write(theArray[i] + " ");
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Array elements are:
        1111 2 3 4 5555
    */

請參閱

參考

陣列 (C# 程式設計手冊)

一維陣列 (C# 程式設計手冊)

多維陣列 (C# 程式設計手冊)

不規則陣列 (C# 程式設計手冊)

概念

C# 程式設計手冊