2007年3月15日星期四

关于 C# 中引用参数的使用(一)

这个名字起得太大了,不知道能写出什么东西来,随便先排个号,大家随便看。
先来一段代码:

1 using System;
2
3 public class A
4 {
5 public static void Method1(ref B b)
6 {
7 b.I = -1;
8 }
9 public static void Method2(B b)
10 {
11 b.I = 100;
12 }
13 public static void Method3(int i)
14 {
15 i = -100;
16 }
17 public static void Method4(ref int i)
18 {
19 i = 1000;
20 }
21 public static void Main()
22 {
23 B b = new B();
24 Console.WriteLine(b.I);//0
25 A.Method1(ref b);
26 Console.WriteLine(b.I);//-1
27 A.Method2(b);
28 Console.WriteLine(b.I);//100
29
30 int i = 0;
31 A.Method3(i);
32 Console.WriteLine(i);//0
33 A.Method4(ref i);
34 Console.WriteLine(i);//1000
35
36 Console.ReadLine();
37 }
38 }
39
40 public class B
41 {
42 private int i;
43 public int I
44 {
45 get {return i;}
46 set {i = value;}
47 }
48 }

大家对24、26、28、32和34行输出的结果没有异议吧。
上面那段代码仅仅说明了一件事情:对于引用类型,不论方法的参数是否是引用参数,传递的都是一个引用;对于值类型,只有当方法的参数是引用参数的时候,才传递引用。
但是有没有例外呢?
。。。。。。下次再说。不知道还会不会有下次。

没有评论: