27th
2008,09
C#编程:使用ref,out关键词定义返回值函数
继上一篇C#编程:使用params关键词定义返回值函数接着说自定义函数的后两种方法.
举例子来说明下用ref关键词来定义函数即引用参数和值参数:
- static int xValue(ref int num, ref int num2)
- {
- num = 2 * num;
- num2 = 2 * num2;
- return num;
- }
- static void Main(string[] args)
- {
- int num = 5;
- int num2 = 10;
- Console.WriteLine(xValue(ref num, ref num2));
- Console.WriteLine(num + ":" + num2);
- //这时的num=10, num2=20;输出结果:10:20;加上ref后会影响到函数外面的变量
- }
两个注意点:
1:定义函数时.指定参数的数据类型与函数体外面定义的变量类型一致,static int xValue(ref int num, ref int num2)
2:使用此函数时为每个参数加上ref.如果不加的话则不会影响函数外面变量的值
举例子来说明下用out关键词来定义函数即引用参数和值参数:
自定义函数只有返回一个数据.如果想得到函数内的多个数据时使用out关键词来定义函数
- static int MaxValueL(int[] numArry, out int maxIndex, out int maxIndex2)
- {
- int MaxValue = numArry[0];
- maxIndex = 0;
- maxIndex2 = 100;
- for (int i = 1; i < numArry.Length; i++)
- {
- if (MaxValue < numArry[i])
- {
- MaxValue = numArry[i];
- maxIndex = i;
- }
- }
- return MaxValue;
- }
- static void Main(string[] args)
- {
- int maxIndex;
- int maxIndex2;
- int[] numArr = { 14, 3, 34, 11, 99, 33 };
- Console.WriteLine(MaxValueL(numArr, out maxIndex, out maxIndex2));
- //返回函数体内的变量MaxValue
- Console.WriteLine(maxIndex + 1);
- //返回函数体内的变量maxIndex
- Console.WriteLine(maxIndex2);
- //返回函数体内的变量maxIndex2
- Console.ReadKey();
- }
两个注意点:
1:定义函数时.指定输出参数的数据类型与函数体外面定义的变量类型一致,out int maxIndex, out int maxIndex2
2:使用此函数时为想要输出参数加上 out .
这里的输出是指把函数体内的变量输出到函数体外应用.这也关联到了变量的作用域问题.
Name: Cngothic 
































Leave a reply?