ref 参数与 out 参数

来源:互联网 发布:伦敦恐怖袭击 知乎 编辑:程序博客网 时间:2024/04/29 17:13

1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5
 6namespace ConsoleApplication2
 7{
 8    class Program
 9    {
10        /*
11         * ref
12         * 通过值传送变量是默认的,也可以迫使值参数通过引用传送给方法。为此,
13         * 要使用ref关键字,如果把一个参数传递给方法,且这个方法的输入参数前
14         * 带有ref关键字,则该方法对变量所作的任何改变都会影响原来对象的值。
15         * 传递给方法之前,必须初始化变量
16         * 
17         * 
18         * out
19         * 把输出值赋给通过引用传递给方法的变量可以使函数从一个例程中输出多个值,
20         * 这种情况在C风格的语言中很常见,通常,变量通过引用传递的初值并不重要,
21         * 这些值会被函数重写,甚至函数根本没用到过。
22         * 
23         * 如果可以在C#中使用这种约定,就会非常方便。便C#编译器要求变量在被引用
24         * 前必须用一个初值进行初始化,这样做是没有必要的,有时甚至会引起混乱。
25         * 但有一种方法能够简化C#编译器所坚持的输入参数的初始化。
26         * 
27         * 编译器使用out关键字来初始化。当在方法的输入参数前加上out关键字时,传递
28         * 给该方法的变量可以不初始化。该变量通过引用传递,所以在从被调用的方法中
29         * 退出后,方法对该变量进行的任何改变保留下来。在调用方法时还需要要使用
30         * out关键字,正如在定义的时候一样。
31         * */

32        static void Main(string[] args)
33        {
34            int i=0;
35
36            Console.WriteLine("Original value of i:/t" + i);
37            Console.WriteLine("now calling a common function");
38            CommonFunctin(i);
39            Console.WriteLine("now the value of i:/t"+i);
40            //as out para,has no value initialize
41            Console.WriteLine("now calling a outfunction");
42            OutFunction(out i);
43            Console.WriteLine("now the value of i:/t" + i);
44            Console.ReadLine();
45            //as ref para,has value before
46            Console.WriteLine("now calling a reffunction");
47            RefFunction(ref i);
48            Console.WriteLine("now the value of i:/t" + i);
49            Console.ReadLine();
50        }

51        static void OutFunction(out int i)
52        {
53            i = 100;
54        }

55        static void RefFunction(ref int i)
56        {
57            i = 200;
58        }

59        static void CommonFunctin(int i)
60        {
61            i = 999;
62        }

63    }

64}