关于数组传递以及ref,out的例子

数组传递,ref与out的区别是,out可以先不初始化,等传递到调用方法后,再初始化。

ref传递,会影响数组原始值。

下面是一个例子:

        static void Main(string[] args)
{
int[] firstArray = { 1, 2, 3 };
int[] firstArrayCopy = firstArray;
Console.WriteLine("Test passing firstArray reference by
value");
Console.WriteLine("\nContents of firstArray before calling
FirstDouble:\n\t");
for (int i = 0; i < firstArray.Length; i++)
Console.Write("{0} ", firstArray[i]);
FirstDouble(firstArray);
Console.WriteLine("\nContents of firstArray after calling
FirstDouble:\n\t");
for (int i = 0; i < firstArray.Length; i++)
Console.Write("{0} ", firstArray[i]);
if (firstArray == firstArrayCopy)
Console.WriteLine("\n\nThe references refer to the
same array");
else
Console.WriteLine("\n\nThe references refer to the
different array");

int[] secondArray = { 1, 2, 3 };
int[] secondArrayCopy = secondArray;
Console.WriteLine("\nTest passing secondArray reference
by reference");
Console.WriteLine("\nContents of secondArray before
calling SecondDouble:\n\t");
for (int i = 0; i < secondArray.Length; i++)
Console.Write("{0} ", secondArray[i]);
SecondDouble(ref secondArray);
Console.WriteLine("\nContents of secondArray after calling
SecondDouble:\n\t");
for (int i = 0; i < secondArray.Length; i++)
Console.Write("{0} ", secondArray[i]);
if (secondArray == secondArrayCopy)
Console.WriteLine("\n\nThe references refer to the
same array");
else
Console.WriteLine("\n\nThe references refer to the
different array");
}

private static void FirstDouble(int[] array)
{
for (int i = 0; i < array.Length; i++)
array[i] *= 2;
array = new int[] { 11, 12, 13 };
}

private static void SecondDouble(ref int[] array)
{
for (int i = 0; i < array.Length; i++)
array[i] *= 2;
array = new int[] { 11, 12, 13 };
}

运行结果如下:

原文地址:https://www.cnblogs.com/zhoukaiwei/p/2245680.html