ref 和 out 关键字比较怪,他们在方法的参数中使用,今天对他们做了认真的研究
msdn上的定义:
ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。
out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。若要使用 out 参数,方法定义和调用方法都必须显式使用 out 关键字。
做了一个测试代码
1 using System;
2
3 namespace Ref
4 {
5 class Program
6 {
7 public static void Main(string[] args)
8 {
9 int i=10;
10 Console.WriteLine("之前的i={0}",i);
11 RefTest(ref i);
12 Console.WriteLine("之后的i={0}",i);
13
14 int j;
15 OutTest(out j);
16 Console.WriteLine("之后的j={0}",j);
17
18 // TODO: Implement Functionality Here
19
20 Console.Write("Press any key to continue . . . ");
21 Console.ReadKey(true);
22 }
23 private static void RefTest(ref int i)
24 {
25 i+=100;
26 }
27
28 private static void OutTest(out int j)
29 {
30 j=200;
31 }
32 }
33 }
2
3 namespace Ref
4 {
5 class Program
6 {
7 public static void Main(string[] args)
8 {
9 int i=10;
10 Console.WriteLine("之前的i={0}",i);
11 RefTest(ref i);
12 Console.WriteLine("之后的i={0}",i);
13
14 int j;
15 OutTest(out j);
16 Console.WriteLine("之后的j={0}",j);
17
18 // TODO: Implement Functionality Here
19
20 Console.Write("Press any key to continue . . . ");
21 Console.ReadKey(true);
22 }
23 private static void RefTest(ref int i)
24 {
25 i+=100;
26 }
27
28 private static void OutTest(out int j)
29 {
30 j=200;
31 }
32 }
33 }
结果为:
之前的i=10
之后的i=110
之后的j=200
Press any key to continue . . .
如果再在Main()加入这样代码
int k;
OutTest(ref k);
Console.WriteLine("之后的k={0}",k);
OutTest(ref k);
Console.WriteLine("之后的k={0}",k);
出现k未被初始化的提示!
一目了然,ref和out的用法,以及两者之间的差别
本人写的比较浅显,园子里还有很多兄弟的
例如http://www.cnblogs.com/hunts/archive/2007/01/13/619620.html
这里还包括了重载的分析,属性等等。比较全面。。