gpt4 book ai didi

c# - C#中,当一个变量经过一个函数/方法时,原来的变量会不会改变?

转载 作者:行者123 更新时间:2023-12-02 15:53:13 25 4
gpt4 key购买 nike

我对函数如何更改传递给它的变量感到困惑。例如,如果我创建了一个变量 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} 的数组“happiness”并传递了一个函数“SunIsShining”,它将每个值增加 2。之后,我认为数组 happiness 应该仍然为 {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 返回 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));
}

c# online

更多信息我们可以看到

value-types

reference-types

passing-parameters

关于c# - C#中,当一个变量经过一个函数/方法时,原来的变量会不会改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71898623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com