通过引用传递引用vs传递引用值 - C#

use*_*524 3 c# reference ref

问候,

我得到传递值和传递参考之间的差异.但是通过ref传递引用(例如数组)并按值传递数组是我无法理解的.如何通过引用传递引用?

     int[] myArray = {1,2,3};
     PassByVal(myArray);
     PassByRef(ref myArray);

     PassByVal(int[] array)
     {    array = new int[] {7,8,9};   // will not work }

     PassByRef(ref int[] array)
     {    array = new int[] {10,11,12}; }  // will work
Run Code Online (Sandbox Code Playgroud)

Cod*_*aos 8

如果通过引用传递引用,则可以使传递的变量指向新对象.如果按值传递引用,仍可以更改对象的状态,但不能使变量指向其他对象.

例:

void RefByRef(ref object x)
{
  x=new object(2);
}

void RefByValue(object x)
{
 x=new object(2);//Only changes a local variable and gets discarded once the function exits
}

void Test()
{
  object x1=1;
  object x1a=x1;
  RefByRef(ref x1);
  //x1 is now a boxed 2
  //x1a is still a boxed 1


  object x2=1;
  RefByValue(x2);
  //x2 is still a boxed 1
}
Run Code Online (Sandbox Code Playgroud)