除了按引用传递值之外,还可以使用out关键字,指定所给的参数是一个输出参数。out关键字
的使用方式与ref关键字相同(在函数定义和函数调用中用作参数的修饰符)。实际上,它的执行方式
与引用参数完全一样,因为在函数执行完毕后,该参数的值将返回给函数调用中使用的变量。但是,
存在一些重要区别。
- 把未赋值的变量用作ref参数是非法的,但可以把未赋值的变量用作out参数。
- 另外,在函数使用out参数时,out参数必须看作是还未赋值。
即调用代码可以把已赋值的变量用作out参数,存储在该变量中的值会在函数执行时丢失。
例如,考虑前面返回数组中最大值的MaxValue()函数,略微修改该函数,获取数组中最大值的
元素索引。为简单起见,如果数组中有多个元素的值都是这个最大值,只提取第一个最大值的索引。
为此,修改函数,添加一个out参数,如下所示:
static int MaxValue(int[] intArray, out int maxIndex) { int maxVal = intArray[0]; maxIndex = 0; for (int i = 1; i < intArray.Length; i++) { if (intArray[i] > maxVal) { maxVal = intArray[i]; maxIndex = i; } } return maxVal; }
可以采用以下方式使用该函数:
int[] myArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 }; int maxIndex; Console.WriteLine("The maximum value in myArray is {0}", MaxValue(myArray, out maxIndex)); Console.WriteLine("The first occurrence of this value is at element {0}", maxIndex + 1);
结果如下:
The maximum value in myArray is 9 The first occurrence of this value is at element 7
注意,必须在函数调用中使用out关键字,就像ref关键字一样