Laz*_*zlo 7 c# arrays parameter-passing pass-by-reference pass-by-value
假设以下代码没有任何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
}
}
Run Code Online (Sandbox Code Playgroud)
现在让该函数按预期工作,可以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
}
}
Run Code Online (Sandbox Code Playgroud)
现在我很困惑为什么传递函数时数组成员通过引用隐式传递.不是数组值类型?
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
}
}
Run Code Online (Sandbox Code Playgroud)