c# - 通过 ref 传递数组元素

标签 c#

<分区>

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 可以移动它,并相应地更新对它驻留在堆栈上的元素的任何引用

最佳答案

Swap 函数仍然访问数组 3 或 4 次,Swap 函数与更简单的代码相比没有任何性能优势。如果重复使用它可能会有用。

static void Swap(ref int a, ref int b) 
{     
    int temp = a;  //<-- Here, a is in the array
    a=b;           //<-- a and b are in the array
    b=temp;        //<-- b is in the array
}

垃圾收集器不会释放您拥有引用的内存,就像您通过引用传递时一样。

关于c# - 通过 ref 传递数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7807255/

相关文章:

c# - C++ 正则表达式 : convert C# regex to C++ Linux

c# - TreeViewItem 中的背景不是全宽

c# - 如何在 C# 中创建类型化的 IEnumerable?

c# - Visual Studio 无法安装 Android SDK(API 级别 19 和 21)(缺少 extra-android-support)

c# - 如何将 json 数据存储到 MySQL 中

c# - 我们如何从 xml 文件中获取所有子项的值

c# - Xamarin.Forms 中的 Entity Framework 7

c# - SelectedItem.Text 是否在 if 语句中工作?

c# - 从 Windows 应用程序使用 amazon ses 发送电子邮件时调用 SSPI 失败

c# - 如何关闭 AutoMapper 自动列表在 List<T> 和 EntitySet<T> 之间的转换?