1 class Program
2 {
3
4 public delegate void MyDelegate(string str);
5
6 static void Main(string[] args)
7 {
8 //
9 MyDelegate d1 = Print;
10
11 d1("简写的触发");
12 //
13 d1 = new MyDelegate(Print);
14 //
15 d1.Invoke("使用invoke触发");
16
17 //多播委托 如果在此之前没有 赋值操作将会报错
18 d1 += Print;
19
20 d1("触发两次");
21
22 Console.WriteLine("让我们来看一看报错的信息");
23
24 /*
25 MyDelegate d2 = new MyDelegate();
26 d2 += Print; //在compile 阶段就会提示你要赋值
27 **/
28
29 //使用action 来声明委托
30
31 Action<string> action = Print;
32 action("action委托");
33
34 //Func<Treturn,Tin..> 适用于具有返回值的委托
35
36
37 //之前是表明委托如何定义 的, 下面才是委托的真正的用法 ,即 作为一个函数的参数
38 //比如我们在下面定义了一个函数 ,这个函数用于输出
39 //我们给他传入不同的action来输出 ,那就可以达到不同的输出效果
40 ActionPrint(Print,"123");
41 ActionPrint(str=>Console.Write("使用lambda表达式:"+str),"123");
42
43
44 //匿名方法
45 string mid = "中间值";
46 Func<string, string> anonDel = delegate(string str)
47 {
48 str += mid;
49 str += " 添加到这个字符串中";
50 return str;
51 };
52
53 Console.WriteLine(anonDel("123"));
54
55 //lambda 表达式 只要有委托参数类型的地方 ,就可以使用lambda表达式 比如上面的例子
56
57 Func<string, string> anonLambda = str =>
58 {
59 str += mid;
60 str += " 添加到这个字符串中";
61 return str;
62 };
63
64 //甚至如果lambda表达式中只需要一个方法的时候 我们还可以使用最简写的方法齐群 囧 其实就是委托....
65 Action<string> anonAction = Print;
66 Console.Read();
67
68 }
69
70 public static void Print(string str)
71 {
72 Console.WriteLine("输出{0}",str);
73 }
74
75
76 public static void ActionPrint(Action<string> action,string str)
77 {
78 action(str);
79 }
80 }