【轉】使用 ref 和 out 傳遞數組(C# 編程指南)

與全部的 out 參數同樣,在使用數組類型的 out 參數前必須先爲其賦值,即必須由被調用方爲其賦值。例如: c#

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  在將數組傳遞給方法時的用法差別。


在此例中,在調用方(Main 方法)中聲明數組 theArray,並在 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] + " ");
        }
    }
}

Array elements are: ui

1 2 3 4 5 spa

在此例中,在調用方(Main  方法)中初始化數組 theArray ,並經過使用  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] + " ");
        }
    }
}

Array elements are: .net

1111 2 3 4 5555 code

相關文章
相關標籤/搜索