问候,
我明白了按值传递和按引用传递之间的区别。但是通过 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
如果通过引用传递引用,则可以使传入的变量指向新对象。如果按值传递引用,您仍然可以更改对象的状态,但不能使变量指向不同的对象。
Example:
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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)