【转】使用 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

相关文章
相关标签/搜索