方法参数 - C# 参考 | Microsoft Learn
按值传递引用类型时:
如果方法分配参数以引用其他对象,则这些更改在调用方是不可见的。
如果方法修改参数所引用对象的状态,则这些更改在调用方是可见的。
暂时遇到的需要辨析的就这一个地方。参考下面这个microsoft给出的示例会更清晰地理解。
int[] arr = { 1, 4, 5 };
System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr[0]);
Change(arr);
System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr[0]);
static void Change(int[] pArray)
{
pArray[0] = 888; // This change affects the original element.
pArray = new int[5] { -3, -1, -2, -3, -4 }; // This change is local.
System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);
}
/* Output:
Inside Main, before calling the method, the first element is: 1
Inside the method, the first element is: -3
Inside Main, after calling the method, the first element is: 888
*/
按C++的理解,可以直接理解为,传了一个指针进去。此时存在两个指针,一个是main函数里的局部变量arr,一个是Change函数里的局部变量pArray。
Change函数内第一句是在对指针解引用后赋值,指针指向的内存被改变。
第二步是在修改指针本身的值,指针所在的内存被改变(改变的是指针指向的地址。但是,指针pArray只是一个局部变量,它当然不会影响位于函数外面的指针arr)。
那么同理的话,继续按C++理解,按引用传递引用就不难想了,传递的是指针的引用。所以在函数体内改变指针的指向,外部也会跟着变。