C#编程:使用ref,out关键词定义返回值函数
继上一篇C#编程:使用params关键词定义返回值函数接着说自定义函数的后两种方法.
举例子来说明下用ref关键词来定义函数即引用参数和值参数:

  1. static int xValue(ref int num, ref int num2)
  2.         {
  3.             num = 2 * num;
  4.             num2 = 2 * num2;
  5.             return num;
  6.         }
  7.         static void Main(string[] args)
  8.         {
  9.             int num = 5;
  10.             int num2 = 10;
  11.             Console.WriteLine(xValue(ref num, ref num2));
  12.             Console.WriteLine(num + ":" + num2);
  13.             //这时的num=10, num2=20;输出结果:10:20;加上ref后会影响到函数外面的变量
  14.         }

两个注意点:
1:定义函数时.指定参数的数据类型与函数体外面定义的变量类型一致,static int xValue(ref int num, ref int num2)
2:使用此函数时为每个参数加上ref.如果不加的话则不会影响函数外面变量的值

举例子来说明下用out关键词来定义函数即引用参数和值参数:
自定义函数只有返回一个数据.如果想得到函数内的多个数据时使用out关键词来定义函数

  1. static int MaxValueL(int[] numArry, out int maxIndex, out int maxIndex2)
  2.         {
  3.             int MaxValue = numArry[0];
  4.             maxIndex = 0;
  5.             maxIndex2 = 100;
  6.             for (int i = 1; i < numArry.Length; i++)
  7.             {
  8.                 if (MaxValue < numArry[i])
  9.                 {
  10.                     MaxValue = numArry[i];
  11.                     maxIndex = i;
  12.                 }
  13.             }
  14.             return MaxValue;
  15.         }
  16.         static void Main(string[] args)
  17.         {
  18.             int maxIndex;
  19.             int maxIndex2;
  20.             int[] numArr = { 14, 3, 34, 11, 99, 33 };
  21.             Console.WriteLine(MaxValueL(numArr, out maxIndex, out maxIndex2));
  22.             //返回函数体内的变量MaxValue
  23.             Console.WriteLine(maxIndex + 1);
  24.             //返回函数体内的变量maxIndex
  25.             Console.WriteLine(maxIndex2);
  26.             //返回函数体内的变量maxIndex2
  27.             Console.ReadKey();
  28.         }

两个注意点:
1:定义函数时.指定输出参数的数据类型与函数体外面定义的变量类型一致,out int maxIndex, out int maxIndex2
2:使用此函数时为想要输出参数加上 out .
这里的输出是指把函数体内的变量输出到函数体外应用.这也关联到了变量的作用域问题.

, , ,

Del.icio.us Google书签 Digg Live Bookmark Technorati Furl Yahoo书签 Facebook 百度搜藏 新浪ViVi 365Key网摘 天极网摘 和讯网摘 博拉网 POCO网摘 添加到饭否 QQ书签 Digbuzz我挖网

Leave a reply?

Logged in as cngothic. Logout »