<分区>
Possible Duplicate:
C# parameters by reference and .net garbage collection
我正在考虑使用 ref 参数来限制数组的边界检查。例如交换两个元素的代码是:
class Test {
int[] array;
private void qSort() {
...blah...
int temp = array[a];
array[a] = array[b];
array[b] = temp;
}
}
它有 4 个访问数组的权限 替代方案是:
class Test {
int[] array;
private void qSort() {
...blah...
Swap( ref array[a], ref array[b] );
}
static void Swap(ref int a,ref int b) {
int temp = a;
a=b;
GC.Collect(); // suppose this happens
b=temp;
}
}
理论上只有 2 次访问数组
让我感到困惑的是,当我通过 ref 传递数组元素时,我不知道到底发生了什么。如果垃圾收集器启动,在 Swap 函数中执行代码时,是否能够移动数组?或者数组在调用期间被固定?
注意上面的代码是一个简单的测试用例。我想在更复杂的场景中使用它
编辑:正如 BrokenGlass 指出的那样,Eric Lippert 在这里回答了这个问题 C# parameters by reference and .net garbage collection
数组不会被固定,GCollector 可以移动它,并相应地更新对它驻留在堆栈上的元素的任何引用