Why would ref be used for array parameters in C#?

不羁的心 提交于 2019-11-30 05:18:42

问题


I read the page Passing Arrays Using ref and out (C# Programming Guide) and was wondering why we would need to define an array parameter as a ref parameter when it is already a reference type. Won't changes in the callee function be reflected in the caller function?


回答1:


Won't changes in the callee function be reflected in the caller function?

Changes to the contents of the array would be reflected in the caller method - but changes to the parameter itself wouldn't be. So for example:

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

Now if we changed Foo to have a signature of:

public void Foo(ref int[] x)

and changed the calling code to:

Foo(ref original);

then it would print 20.

It's very important to understand the difference between a variable and the object that its value refers to - and likewise between modifying an object and modifying a variable.

See my article on parameter passing in C# for more information.




回答2:


If you only plan to change the contents of the array, then you're correct. However, if you plan on changing the array itself, then you must pass by reference.

For example:

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.
}


来源:https://stackoverflow.com/questions/19257079/why-would-ref-be-used-for-array-parameters-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!