在微软web的例子中有如下代码:
class TestRef
{
static void FillArray(ref int[] arr)
{
// Create the array on demand:
if (arr == null)
{
arr = new int[10];
}
// Fill the array:
arr[0] = 1111;
arr[4] = 5555;
}
}
如果我删除 if (arr == null)
行,错误输出将是 0 0 0 0 0
而不是 1 2 3 4 5
。为什么?
最佳答案
这是因为您通过 ref
传递,这意味着您正在更改 main
方法中该变量的指针。
您正在将其分配给一个新的 int[]
,该 int[]
填充了 int
的默认值,即 0
关于c# - 按引用调用未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24156222/