我阅读了传递数组的页面使用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#中传递参数的文章.
如果您只打算更改数组的内容,那么您是正确的.但是,如果您打算更改数组本身,则必须通过引用传递.
例如:
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)
| 归档时间: |
|
| 查看次数: |
4299 次 |
| 最近记录: |