1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5
6namespace AnonymousExample
7{
8 //测试代码
9 class Test
10 {
11 //带有名称的方法
12 public static int DoubleMethod(int i)
13 {
14 i = i * 2;
15 return i;
16 }
17
18 //定义一个委托
19 public delegate int CommonDelegate(int i);
20
21 static void Main( )
22 {
23 int i = 100;
24 //一般委托
25 CommonDelegate cd = new CommonDelegate(DoubleMethod);
26 Console.WriteLine(cd(i));
27 Console.WriteLine(i);
28 Console.WriteLine(cd(i));
29 Console.WriteLine(i);
30 Console.WriteLine();
31
32 //匿名方法
33 cd = delegate
34 {
35 i = i * 2;
36 return i;
37 };
38 Console.WriteLine(cd(i));
39 Console.WriteLine(i);
40 Console.WriteLine(cd(i));
41 Console.WriteLine(i);
42 Console.WriteLine();
43 Console.Read();
44 }
45 }
46}
47
运行结果如下:2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5
6namespace AnonymousExample
7{
8 //测试代码
9 class Test
10 {
11 //带有名称的方法
12 public static int DoubleMethod(int i)
13 {
14 i = i * 2;
15 return i;
16 }
17
18 //定义一个委托
19 public delegate int CommonDelegate(int i);
20
21 static void Main( )
22 {
23 int i = 100;
24 //一般委托
25 CommonDelegate cd = new CommonDelegate(DoubleMethod);
26 Console.WriteLine(cd(i));
27 Console.WriteLine(i);
28 Console.WriteLine(cd(i));
29 Console.WriteLine(i);
30 Console.WriteLine();
31
32 //匿名方法
33 cd = delegate
34 {
35 i = i * 2;
36 return i;
37 };
38 Console.WriteLine(cd(i));
39 Console.WriteLine(i);
40 Console.WriteLine(cd(i));
41 Console.WriteLine(i);
42 Console.WriteLine();
43 Console.Read();
44 }
45 }
46}
47
一般委托时,委托对象cd 封装的是命名方法,变量 i 只是作为形式参数以值的形式传递给方法,调用后不会修改 i 的值;而当
cd 封装的是匿名方法时,i 就是匿名方法的外部变量,它被执行代码“捕获”,外部变量被匿名方法直接引用,于是调用后 i 值也修改了。