by ref vs. by val, variable vs. array
This question already has an answer here:
When reference type object is passed by value, the reference to object is actually passed by value, so if you update the reference to a new object inside the method implementation the reference will start pointing to new memory address.
You can see the difference in results by modifying a little the method implementation, so that initialize the coming input array to a new instance like:
static void method1(int[] z)
{
z = new int[3]; // new instance created and z has reference to it
// while calling side still refers to old memory location
// which is { 13, 1, 5 }
for(int m=0; m<z.Length;m++)
{
z[m] *= 2;
}
}
now when you call the pass by value method it will modify the z
just locally for this method and the outer array would not be affected while if you pass it by reference then both array will get impacted with the changes.
What is happening is that we are setting the array z
to reference to new memory location by creating a new array instance, so the reference in method gets updated to point to new memory location but the calling side reference is still pointing to the old array which was instantiated before calling the method.
When you are passing by reference the both the variable will get updated to point to the new memory location.
static void method1(ref int[] z)
{
z = new int[3]; // new instance created and z has reference to it
// now calling side also refers to new memory location
// which is new int[3];
for(int m=0; m<z.Length;m++)
{
z[m] *= 2;
}
}
链接地址: http://www.djcxy.com/p/21016.html
上一篇: 通过值传递的参数,仍然在函数内改变?
下一篇: 通过ref与val,变量与数组