我想做一些数组传递给.NET函数,我有点困惑。数组是引用类型,因此对传递给该函数的数组所做的更改在函数外部是可见的。例如传递数组的功能有或没有参考关键字
static void Main(string[] args)
{
byte[] arr = new byte[] { 1,2, 3, 4, 5 };
Console.WriteLine(string.Join("", arr)); //console output: 12345
doSomething(arr);
Console.WriteLine(string.Join("", arr)); //console output: 52341
}
static void doSomething(byte[] array)
{
byte tmp = array[0];
array[0] = array[array.Length - 1];
array[array.Length - 1] = tmp;
}
所以它的工作原理完全一样,与(同一控制台输出)
doSomething(ref arr); for static void doSomething(ref byte[] array)
但是用“裁判”的关键字,如果我添加下面一行到我的功能:
array = (new byte[] { 1 }).Concat(array).ToArray(); //size of array is changed
结果是不同的:
12345
52341// "ref" keyword is not used
和
12345
152341 "ref" keyword is used
有人能解释我为什么结果不同吗?
[参数传递在C#](http://www.yoda.arachsys.com/csharp/parameters.html#ref) – sll