为什么ref将用于C#中的数组参数?

Tyl*_*den 6 c# ref out

我阅读了传递数组的页面使用ref和out(C#编程指南),并想知道为什么我们需要将数组参数定义为ref参数(当它已经是引用类型时).被调用函数中的更改不会反映在调用函数中吗?

Jon*_*eet 26

被调用函数中的更改不会反映在调用函数中吗?

对数组内容的更改将反映在调用方法中 - 但是对参数本身的更改不会.例如:

public void Foo(int[] x)
{
    // The effect of this line is visible to the caller
    x[0] = 10;

    // This line is pointless
    x = new int[] { 20 };
}
...
int[] original = new int[10];
Foo(original);
Console.WriteLine(original[0]); // Prints 10
Run Code Online (Sandbox Code Playgroud)

现在,如果我们改为Foo签名:

public void Foo(ref int[] x)
Run Code Online (Sandbox Code Playgroud)

并将调用代码更改为:

Foo(ref original);
Run Code Online (Sandbox Code Playgroud)

然后它将打印20.

理解变量与其值所引用的对象之间的差异非常重要 - 同样在修改对象和修改变量之间也是如此.

有关更多信息,请参阅我在C#中传递参数的文章.

  • @TrevorElliott:当然它不会真正"替换数组" - 它会改变引用数组的单个变量的值,并将其用作参数.引用原始数组的任何*其他*变量*仍然*引用原始数组. (3认同)
  • 要详细说明......使用数组,传统上不能在不创建全新数组的情况下修改大小.因此,当您想要使用新数组替换它以有效地更改大小时,您可能希望使用ref或out关键字. (2认同)

poy*_*poy 5

如果您只打算更改数组的内容,那么您是正确的.但是,如果您打算更改数组本身,则必须通过引用传递.

例如:

void foo(int[] array)
{
  array[0] = 5;
}

void bar(int[] array)
{
  array = new int[5];
  array[0] = 6;
}

void barWithRef(ref int[] array)
{
  array = new int[6];
  array[0] = 6;
}


void Main()
{
  int[] array = int[5];
  array[0] = 1;

  // First, lets call the foo() function.
  // This does exactly as you would expect... it will
  // change the first element to 5.
  foo(array);

  Console.WriteLine(array[0]); // yields 5

  // Now lets call the bar() function.
  // This will change the array in bar(), but not here.
  bar(array);

  Console.WriteLine(array[0]); // yields 1.  The array we have here was never changed.

  // Finally, lets use the ref keyword.
  barWithRef(ref array);

  Console.WriteLine(array[0]); // yields 5.  And the array's length is now 6.
}
Run Code Online (Sandbox Code Playgroud)