ref 参数与 out 参数

来源:互联网 发布:淘宝客怎么玩才能赚钱 编辑:程序博客网 时间:2024/04/29 22:24
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace ConsoleApplication2
  6. {
  7.    class Program
  8.    {
  9.         /**//*
  10.          * ref
  11.          * 通过值传送变量是默认的,也可以迫使值参数通过引用传送给方法。为此,
  12.          * 要使用ref关键字,如果把一个参数传递给方法,且这个方法的输入参数前
  13.          * 带有ref关键字,则该方法对变量所作的任何改变都会影响原来对象的值。
  14.          * 传递给方法之前,必须初始化变量
  15.          * 
  16.          * 
  17.          * out
  18.          * 把输出值赋给通过引用传递给方法的变量可以使函数从一个例程中输出多个值,
  19.          * 这种情况在C风格的语言中很常见,通常,变量通过引用传递的初值并不重要,
  20.          * 这些值会被函数重写,甚至函数根本没用到过。
  21.          * 
  22.          * 如果可以在C#中使用这种约定,就会非常方便。便C#编译器要求变量在被引用
  23.          * 前必须用一个初值进行初始化,这样做是没有必要的,有时甚至会引起混乱。
  24.          * 但有一种方法能够简化C#编译器所坚持的输入参数的初始化。
  25.          * 
  26.          * 编译器使用out关键字来初始化。当在方法的输入参数前加上out关键字时,传递
  27.          * 给该方法的变量可以不初始化。该变量通过引用传递,所以在从被调用的方法中
  28.          * 退出后,方法对该变量进行的任何改变保留下来。在调用方法时还需要要使用
  29.          * out关键字,正如在定义的时候一样。
  30.          * */
  31.         static void Main(string[] args)
  32.         {
  33.             int i=0;
  34.             Console.WriteLine("Original value of i:/t" + i);
  35.             Console.WriteLine("now calling a common function");
  36.             CommonFunctin(i);
  37.             Console.WriteLine("now the value of i:/t"+i);
  38.             //as out para,has no value initialize  
  39.             Console.WriteLine("now calling a outfunction");
  40.             OutFunction(out i);
  41.             Console.WriteLine("now the value of i:/t" + i);
  42.             Console.ReadLine();
  43.             //as ref para,has value before  
  44.             Console.WriteLine("now calling a reffunction");
  45.             RefFunction(ref i);
  46.             Console.WriteLine("now the value of i:/t" + i);
  47.             Console.ReadLine();
  48.         }
  49.         static void OutFunction(out int i)
  50.         {
  51.             i = 100;
  52.         }
  53.         static void RefFunction(ref int i)
  54.         {
  55.             i = 200;
  56.         }
  57.         static void CommonFunctin(int i)
  58.         {
  59.             i = 999;
  60.         }
  61.     }
  62. }