1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5:
6: namespace CSharp.Delegate
7: {
8: //声明委托
9: public delegate void Del(string message);
10:
11: class Program
12: {
13: // Create a method for a delegate.
14: public static void DelegateMethod(string message)
15: {
16: System.Console.WriteLine(message);
17: }
18:
19: //定义回调方法
20: public static void MethodWithCallback(string message, Del callback)
21: {
22: callback(message);
23: }
24:
25: public static void Hello(string s)
26: {
27: System.Console.WriteLine(" Hello, {0}!", s);
28: }
29:
30: public static void Goodbye(string s)
31: {
32: System.Console.WriteLine(" Goodbye, {0}!", s);
33: }
34:
35: static void Main(string[] args)
36: {
37:
38: //new方法实例化委托,将方法作为参数进行传递
39: Del handler = new Del(DelegateMethod);
40: handler("向大家问个好吧。");
41: MethodWithCallback("大家好!", handler);
42:
43: //匿名方法来实例化委托
44: Del anotherhandler = DelegateMethod;
45: anotherhandler("Hello World");
46: MethodWithCallback("I am coming!", anotherhandler);
47:
48: //“Lambda 表达式”是一个匿名函数,可以其表达式分配给委托类型
49: Del lamDel = (string s) =>
50: {
51: Console.WriteLine(s);
52: };
53: lamDel("我是Lambda匿名委托!");
54:
55: //
56: //多路组合委托
57: //
58: //Hello,Goodbye,DelegateMethod 组合委托到d
59: Del d;
60: d = Hello;
61: d += Goodbye;
62: d += new Del(DelegateMethod);
63:
64: d("David");
65:
66: //移除委托DelegateMethod
67: d -= DelegateMethod;
68: d("David");
69:
70: }
71: }
72: }