使用 ref 和 out 传递数组

 

与所有的 out 参数一样,在使用数组类型的 out 参数前必须先为其赋值,即必须由接受方为其赋值。例如:

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

与所有的 ref 参数一样,数组类型的 ref 参数必须由调用方明确赋值。因此不需要由接受方明确赋值。可以将数组类型的 ref 参数更改为调用的结果。例如,可以为数组赋以 null 值,或将其初始化为另一个数组。例如:

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

下面的两个示例说明 outref 在将数组传递给方法上的用法差异。

示例 1

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

// cs_array_ref_and_out.cs
using System; 
class TestOut 
{
   
static public void FillArray(out int[] myArray) 
   
{
      
// Initialize the array:
      myArray = new int[5{12345};
   }


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

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

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

}


输出

Array elements are:
1
2
3
4
5

示例 2

在此例中,在调用方(Main 方法)中初始化数组 myArray,并通过使用 ref 参数将其传递给 FillArray 方法。在 FillArray 方法中更新某些数组元素。然后将数组元素返回调用方并显示。

// cs_array_ref_and_out2.cs
using System; 
class TestRef 
{
   
public static void FillArray(ref int[] arr) 
   
{
      
// Create the array on demand:
      if (arr == null)
         arr 
= new int[10];
      
// Otherwise fill the array:
      arr[0= 123;
      arr[
4= 1024;
   }


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

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

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

}

输出

Array elements are:
123
2
3
4
1024
posted @ 2005-07-11 18:58  Elaine Shi  阅读(264)  评论(0编辑  收藏  举报