一个C#实现的最简单的委托例子
1using System;
2
3namespace DelegateSample
4{
5 public delegate void PrintCallback(int number);
6
7 public class Printer{
8
9 //委托定义
10 private PrintCallback _print;
11
12 //委托将要依附的属性
13 public PrintCallback PrintCallback{
14 get{return _print;}
15 set{_print=value;}
16 }
17 }
18
19 public class Driver{
20
21 //将要委托的事件
22 private void PrintInteger(int number){
23 Console.WriteLine("From PrintInteger:The number is {0}.", number);
24 }
25
26 static void Main(string[] args){
27 Driver driver = new Driver();
28 Printer printer=new Printer();
29
30 //将委托绑定到属性
31 printer.PrintCallback = new PrintCallback(driver.PrintInteger);
32
33 //使用属性触发委托事件
34 printer.PrintCallback(10);
35 printer.PrintCallback(100);
36
37 Console.WriteLine("press Enter to exit");
38 Console.ReadLine();
39 }
40 }
41
42}
43
44结果:
45From PrintInteger:The number is 10.
46From PrintInteger:The number is 100.
47press Enter to exit
48
49
2
3namespace DelegateSample
4{
5 public delegate void PrintCallback(int number);
6
7 public class Printer{
8
9 //委托定义
10 private PrintCallback _print;
11
12 //委托将要依附的属性
13 public PrintCallback PrintCallback{
14 get{return _print;}
15 set{_print=value;}
16 }
17 }
18
19 public class Driver{
20
21 //将要委托的事件
22 private void PrintInteger(int number){
23 Console.WriteLine("From PrintInteger:The number is {0}.", number);
24 }
25
26 static void Main(string[] args){
27 Driver driver = new Driver();
28 Printer printer=new Printer();
29
30 //将委托绑定到属性
31 printer.PrintCallback = new PrintCallback(driver.PrintInteger);
32
33 //使用属性触发委托事件
34 printer.PrintCallback(10);
35 printer.PrintCallback(100);
36
37 Console.WriteLine("press Enter to exit");
38 Console.ReadLine();
39 }
40 }
41
42}
43
44结果:
45From PrintInteger:The number is 10.
46From PrintInteger:The number is 100.
47press Enter to exit
48
49