1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ActionDelegate
7 {
8 delegate void OutputInfo(string str,int count);
9
10 class Program
11 {
12 private static string str = "hello world";
13 private static int count = 0;
14 static void Main(string[] args)
15 {
16 //Test0();
17 //Test1();
18 //Test2();
19 //Test3();
20 //Test4();
21 Test5();
22 Console.ReadKey();
23 }
24
25 /// <summary>
26 /// 显式声明委托
27 /// </summary>
28 protected static void Test0()
29 {
30 OutputInfo target = Output;
31 target(str, ++count);
32 }
33
34 protected static void Test1()
35 {
36 Action<string, int> target; //申明只有一个参数的委托,返回值必须为void
37 target = Output;
38 target(str, ++count);
39 }
40
41 protected static void Test2()
42 {
43 Action<string, int> target; //申明只有一个参数的委托
44 target = delegate(string s, int c) { Output(s, c); }; //匿名方法
45 target(str, ++count);
46 }
47
48 protected static void Test3()
49 {
50 Action<string, int> target; //申明只有一个参数的委托
51 target = (s, c) => Output(s, c); //lambda表达式
52 target(str, ++count);
53 }
54
55 /// <summary>
56 /// 委托方法
57 /// </summary>
58 /// <param name="str"></param>
59 protected static void Output(string str, int count)
60 {
61 Console.WriteLine("method-{0}:{1}", count, str);
62 }
63
64 /// <summary>
65 /// 委托方法2
66 /// </summary>
67 /// <param name="str"></param>
68 protected static void Output2(string str)
69 {
70 Console.WriteLine(str);
71 }
72
73 protected static void Test4()
74 {
75 List<String> names = new List<String>();
76 names.Add("Bruce");
77 names.Add("Alfred");
78 names.Add("Tim");
79 names.Add("Richard");
80
81 // Display the contents of the list using the Print method.
82 names.ForEach(Output2);
83
84 // The following demonstrates the anonymous method feature of C#
85 // to display the contents of the list to the console.
86 names.ForEach(delegate(String name)
87 {
88 Console.WriteLine(name);
89 });
90 }
91
92 protected static void Test5()
93 {
94 MyClass myClass = new MyClass();
95 myClass.myDelegate();
96 }
97 }
98 }