ref和out

传递到 ref 参数的参数必须最先初始化。这与out不同,out 的参数在传递之前不需要显式初始化。尽管 ref  out 在运行时的处理方式不同,但它们在编译时的处理方式是相同的。因此,如果一个方法采用 ref 参数,而另一个方法采用 out参数,则无法重载这两个方法。

示例 1


在此例中,在调用方(Main 方法)中声明数组 theArray,并在 FillArray 方法中初始化此数组。然后将数组元素返回调用方并显示。

class TestOut

{

    static void FillArray(out int[] arr)

    {

        //初始化数组:

        arr = new int[5] { 1, 2, 3, 4, 5 };

    }

 

    static void Main()

    {

        int[] theArray; //不必需初始化

 

        // Pass the array to the callee using out:

        FillArray(out theArray);

 

        // 输出数组:

        System.Console.WriteLine("Array elements are:");

        for (int i = 0; i < theArray.Length; i++)

        {

            System.Console.Write(theArray[i] + " ");

        }

    }

}

 

输出 1


Array elements are:

1 2 3 4 5

示例 2


在此例中,在调用方(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()

    {

        // 必需初始化数组:

        int[] theArray = { 1, 2, 3, 4, 5 };

 

        // 传递参数使用 ref:

        FillArray(ref theArray);

 

        // 输出数组:

        System.Console.WriteLine("Array elements are:");

        for (int i = 0; i < theArray.Length; i++)

        {

            System.Console.Write(theArray[i] + " ");

        }

    }

}

 

输出 2


Array elements are:

1111 2 3 4 5555

 

来源MSDN 

posted @ 2010-08-06 20:52  梅子  阅读(299)  评论(0编辑  收藏  举报