所谓委托,可以当作是一个指向函数的指针,但是C#的委托可以同时指向多个函数,也就是支持多路广播。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1
class MathClass
2 {
3 public delegate int DelClick( int a);
4
5 public static int D1( int input)
6 {
7 Console.WriteLine(input);
8 return input;
9 }
10
11 public static int D2( int input)
12 {
13 Console.WriteLine(input+ 1);
14 return input+ 1;
15 }
16
17 public DelClick delClick = new DelClick(D1);
18 public void Click( int a)
19 {
20 Console.WriteLine( " 委托开始 ");
21 int i=delClick.Invoke(a);
22 Console.WriteLine( " i{0} ", i);
23 Console.WriteLine( " 委托结束 ");
24
25 }
26
27 static void Main()
28 {
29 MathClass m = new MathClass();
30 m.delClick += D2;
31 m.Click( 3);
2 {
3 public delegate int DelClick( int a);
4
5 public static int D1( int input)
6 {
7 Console.WriteLine(input);
8 return input;
9 }
10
11 public static int D2( int input)
12 {
13 Console.WriteLine(input+ 1);
14 return input+ 1;
15 }
16
17 public DelClick delClick = new DelClick(D1);
18 public void Click( int a)
19 {
20 Console.WriteLine( " 委托开始 ");
21 int i=delClick.Invoke(a);
22 Console.WriteLine( " i{0} ", i);
23 Console.WriteLine( " 委托结束 ");
24
25 }
26
27 static void Main()
28 {
29 MathClass m = new MathClass();
30 m.delClick += D2;
31 m.Click( 3);
33 Console.ReadLine();
34 }
35 }
34 }
35 }
如上示例,输出的结果如下
委托开始
3
4
i4
委托结束
我们可以看到,当多路广播时,委托返回的是最后一个广播的值。