C# 个人笔记

方法参数 - 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++理解,按引用传递引用就不难想了,传递的是指针的引用。所以在函数体内改变指针的指向,外部也会跟着变。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值