我对函数如何更改通过它传递的变量感到困惑。例如,如果我创建了一个变量 t = 1,并通过向其添加 2 来传递一个函数,在函数内部 t 是 3,但在 Main 函数中 t 仍然是 1:
static void Main(string[] args)
{
int t = 1;
addTwo(t);
Console.WriteLine(t);
## t=1
Console.ReadLine();
}
static void addTwo(int t)
{
t+=2;
Console.WriteLine("inside function {0}",t);
## t=3
函数内部 t 的值为 3,但 Main 中的值保持为 1。
但是,如果我创建了一个值为 {2,3,4,5,6} 的数组“幸福”并通过一个函数“SunIsShining”,它将每个值增加 2。之后,我认为数组幸福应该仍然是 {2 ,3,4,5,6}。然而它变成了{4,5,6,7,8}。
static void Main(string[] args)
{
int[] happiness = { 2, 3, 4, 5, 6 };
SunIsShining(happiness);
## happiness = { 4, 5, 6, 7, 8 }
foreach (int y in happiness)
{
Console.WriteLine(y);
}
Console.ReadLine();
}
static void SunIsShining(int[] x)
{
for (int i = 0; i < x.Length; i++)
x[i] += 2;
}
谁能帮我理解原因?谢谢!
因为
int[]
是一种可能将对象引用传递给函数的引用类型,因此您可以修改同一数组中的值。
int
是一种值类型,它会在传递给函数之前克隆值,因此您修改的值不是t
来自Main
函数。
我们可以通过这个示例代码通过ReferenceEquals
方法来证明,将比较对象引用是否与下面的相同,假设我们可以看到addTwo
是 return false
,但SunIsShining
返回 true。
static int t1;
static int[] happiness;
static void Main(string[] args)
{
t1 = 1;
happiness = new int[]{ 2, 3, 4, 5, 6 };
addTwo(t1);
SunIsShining(happiness);
Console.ReadLine();
}
static void addTwo(int t)
{
t+=2;
Console.WriteLine("Is same object by value?" + object.ReferenceEquals(t1,t));
}
static void SunIsShining(int[] x)
{
Console.WriteLine("Is same object by refer?" + object.ReferenceEquals(happiness,x));
}
更多信息我们可以看到
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句