如果我们在方法中修改作为参数传递的数组的内容,修改会在参数的副本上进行,而不是在原始参数上进行,因此结果不可见。
当我们调用具有引用类型参数的方法时,会发生什么过程?
下面是我想要询问的代码示例:
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);
}
}
}
ref
或out
,否则它将被按值传递。如果你仍然不信服,我建议你阅读C#规范的相关部分。 - InBetweena = null
,当方法返回时,调用点的变量将是null
。在你的示例中尝试一下,看看它是如何工作的。再次阅读我之前回答中的链接。 - InBetween