1
using System;
2
3
namespace ConsoleApplication1
4
{
5
public delegate void PrintCallback(int number);
6
7
public class Printer
8
{
9
private PrintCallback _print;
10
11
public PrintCallback PrintCallback
12
{
13
get {return _print;}
14
set {_print = value;}
15
}
16
}
17
18
class Driver
19
{
20
private void PrintInteger(int number)
21
{
22
Console.WriteLine("The number is {0}",number);
23
}
24
25
static void Main(string[] args)
26
{
27
Driver driver = new Driver();
28
Printer printer = new Printer();
29
printer.PrintCallback = new PrintCallback(driver.PrintInteger);
30
printer.PrintCallback(10);
31
printer.PrintCallback(1000);
32
}
33
}
34
}
35

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

这个例子所做的事情就是:定义了一个名为PrintCallback的委托;Printer类具有PrintCallback类型的委托属性PrintCallback。Driver类定义了一个PrintInteger方法,再Main方法中,Driver类将Printer实例的PrintCallback委托绑定到PrintInteger方法。
现在无论什么时候调用PrintCallback委托,它所绑定的方法PrintInteger就会被执行。
------------------------------------------------------------------------------------------------------
委托是用来处理其他语言(如 C++、Pascal 和 Modula)需用函数指针来处理的情况的。不过与 C++ 函数指针不同,委托是完全面对对象的;另外,C++ 指针仅指向成员函数,而委托同时封装了对象实例和方法。
委托实例封装一个调用列表,该列表列出一个或多个方法,其中每个方法均作为一个可调用实体来引用。