这些是我正在阅读的 ac# 书中的示例,只是在理解这个示例实际在做什么时遇到了一些困难,希望得到一个解释,以帮助我进一步了解这里发生的事情。
//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。
提前致谢