mda*_*019 3 c# arrays arguments parameter-passing
如果我们修改在方法内作为参数传递的数组的内容,则对参数的副本而不是原始参数进行修改,因此结果不可见.
当我们调用具有引用类型参数的方法时,会发生什么过程?
这是我想问的代码示例
using System;
namespace Value_Refrence_Type
{
class Program
{
public static void Main()
{
int[] callingarray = { 22, 200, 25485 };
abc(callingarray);
Console.WriteLine("This is callingarray");
foreach (int element in callingarray)
Console.WriteLine(element);
}
//method parameter
static void abc(int[] calledarray)
{
Console.WriteLine("Method Called--------");
foreach (int element in calledarray)
Console.WriteLine(element);
//Here on changing the value of elements of calledarray does't afftect the value of element of callingarray
//if both refrences to same memory location then the value needs to change, which is not happening here
calledarray = new int[] {55, 54, 65};
foreach (int element in calledarray)
Console.WriteLine(element);
}
}
}
Run Code Online (Sandbox Code Playgroud)
不,这不正确.
默认情况下,参数在C#中按值传递,这意味着您将获得变量的副本.但重要的是要意识到复制的只是变量,不一定是对象; 如果变量包含引用类型(例如数组),则变量实际上只是对象所在的内存地址的"指针".因此,当您将所述变量传递给方法调用时,引用将被复制为yes,但它仍然指向原始变量引用的完全相同的对象.
当参数是值类型时,情况就大不相同了.在这种情况下,变量本身保存对象,因此您将获得您似乎期望的行为.
这里有许多答案和描述.我试着举个例子.让我们说这是你的方法:
public void ProcessData(int[] data)
{
data[0] = 999;
}
Run Code Online (Sandbox Code Playgroud)
如果你调用这样的方法:
int[] dataToProcess = new int[] {1, 2, 3};
ProcessData(dataToProcess);
Console.WriteLine(dataToProcess[0]); //returns 999;
Run Code Online (Sandbox Code Playgroud)
它将返回999因为ProcessData访问数组的内存.
像@InBetween描述的那样:
默认情况下,在C#中通过副本传递参数,但复制的是变量
这意味着,如果将方法中的数据设置为null:
public void ProcessData(int[] data)
{
data = null;
}
Run Code Online (Sandbox Code Playgroud)
它不会将您设置dataToProcess为null.这意味着:
您将指向数组内存的指针的副本传递给方法.
| 归档时间: |
|
| 查看次数: |
29567 次 |
| 最近记录: |