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.如果不加的话则不会影响函数外面变量的值
Read the rest of this entry »

, , ,