1
using System;
2
3
namespace 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
结果:
45
From PrintInteger:The number is 10.
46
From PrintInteger:The number is 100.
47
press Enter to exit
48
49

2

3

4



5

6

7



8

9

10

11

12

13



14



15



16

17

18

19



20

21

22



23

24

25

26



27

28

29

30

31

32

33

34

35

36

37


38

39

40

41

42

43

44

45

46

47


48

49
