gpt4 book ai didi

c# - C# : why is it implicitly by reference? 传入数组参数

转载 作者:太空狗 更新时间:2023-10-29 19:53:20 26 4
gpt4 key购买 nike

假设下面的代码,没有任何 ref 关键字,显然不会替换传递的变量,因为它是作为值传递的。

class ProgramInt
{
public static void Test(int i) // Pass by Value
{
i = 2; // Working on copy.
}

static void Main(string[] args)
{
int i = 1;
ProgramInt.Test(i);
Console.WriteLine(i);
Console.Read();

// Output: 1
}
}

现在要让该函数按预期工作,可以像往常一样添加 ref 关键字:

class ProgramIntRef
{
public static void Test(ref int i) // Pass by Reference
{
i = 2; // Working on reference.
}

static void Main(string[] args)
{
int i = 1;
ProgramInt.Test(ref i);
Console.WriteLine(i);
Console.Read();

// Output: 2
}
}

现在我很困惑为什么传入函数的数组成员是通过引用隐式传递的。数组不是值类型吗?

class ProgramIntArray
{
public static void Test(int[] ia) // Pass by Value
{
ia[0] = 2; // Working as reference?
}

static void Main(string[] args)
{
int[] test = new int[] { 1 };
ProgramIntArray.Test(test);
Console.WriteLine(test[0]);
Console.Read();

// Output: 2
}
}

最佳答案

不,数组是类,这意味着它们是引用类型。

关于c# - C# : why is it implicitly by reference? 传入数组参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3604397/

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