这些是我正在阅读的一本c#书籍中的示例,它只是为了解这个示例实际正在做的事情而有点麻烦,希望能够帮助我进一步理解这里发生的事情。通过数值和引用传递数组
//creates and initialzes firstArray
int[] firstArray = { 1, 2, 3 };
//Copy the reference in variable firstArray and assign it to firstarraycopy
int[] firstArrayCopy = firstArray;
Console.WriteLine("Test passing firstArray reference by value");
Console.Write("\nContents of firstArray " +
"Before calling FirstDouble:\n\t");
//display contents of firstArray with forloop using counter
for (int i = 0; i < firstArray.Length; i++)
Console.Write("{0} ", firstArray[i]);
//pass variable firstArray by value to FirstDouble
FirstDouble(firstArray);
Console.Write("\n\nContents of firstArray after " +
"calling FirstDouble\n\t");
//display contents of firstArray
for (int i = 0; i < firstArray.Length; i++)
Console.Write("{0} ", firstArray[i]);
// test whether reference was changed by FirstDouble
if (firstArray == firstArrayCopy)
Console.WriteLine(
"\n\nThe references refer to the same array");
else
Console.WriteLine(
"\n\nThe references refer to different arrays");
//method firstdouble with a parameter array
public static void FirstDouble(int[] array)
{
//double each elements value
for (int i = 0; i < array.Length; i++)
array[i] *= 2;
//create new object and assign its reference to array
array = new int[] { 11, 12, 13 };
基本上没有,我想知道是什么代码是,如果阵列由值比原来的调用者传递没有得到通过方法(据我所知)修改书说。因此,在方法FirstDouble结束时,他们尝试将局部变量数组分配给一组失败的元素,并在显示时原始调用方的新值为2,4,6。
现在我的困惑是,方法FirstDouble中的for循环如何将原始调用方firstArray修改为2,4,6(如果它是通过值传递的)。我认为价值应该保持在1,2,3。
在此先感谢
可能重复的[值类型和引用类型问题](http://stackoverflow.com/questions/6070892/value-type-and-reference-type-problem) – 2012-04-25 23:50:11
@AlexeiLevenkov在其他地方覆盖如此之好,我'd讨厌关闭那一个:( – 2012-04-26 00:10:34