ASP.NET 复习第二天 数组(3)
时间:2011-03-14 来源:星尘
使用ref和out传递数组
与所有的out参数一样,在使用数组类型的out参数前必须先为其赋值,即必须由被调用方为其赋值。例如:static void TestMethod1(out int[] arr)
{
//definite assignment of array
arr = new int[10];
}
与所有的ref参数一样,数组类型的ref参数必须由调用方明确赋值。因此不需要由接受方明确赋值。可以将数组类型的ref参数更改为调用的结果。
例如,可以为数组赋以null值,或将其初始化为另一个数组。例如:
static void TestMethod2(ref int[] arr)
{
// arr initalized to a different array
arr = new int[10];
}
下面我们用2个示例来说明out与ref在将数组传递给方法时的用法差异。
在此例中,在调用方(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;
FillArray(out theArray);
System.Console.WriteLine("Array elements are:");
for(int i=0;i<theArray.Length;i++)
{
System.Console.Write(theArray[i] +" ");
}
System.Console.WriteLine("Press any key to exit.");
}
}
在下例中,在调用方(Main方法)中初始化数组theArray,并通过使用ref参数将其传递给FillArray方法。 在FillArray方法中更新某些数组元素。然后将数组元素返回调用并显示。
class TestRef
{
static void FillArray(ref int[] arr)
{
int (arr == null)
arr = new int[10];
}
arr[0] = 1111;
arr[4] = 5555;
}
static void Main()
{
int[] theArray = {1,2,3,4,5};
FillArray(ref theArray);
System.Console.WriteLine("Array elements are:");
for (int i = 0; i < theArray.Length; i++)
{
System.Console.Write(theArray[i] + " ");
}
}
PS:注意理解out与ref的不同。
相关阅读 更多 +










