C# 委托 应用实例

用一句话解释委托:委托是一种可以把引用存储为函数的类型。

有些类似Spring框架对于接口的用法,向Action中注入Service对象。Action并不知道调用哪个服务层,只有容器通过配置文件

向Action注入Service对象后,Action才能知道调用的是哪个实现的服务层对象。

你传入的是那个实现类,我就执行哪个实现类的方法。

从网上搜得一段说明,帮助理解:

委托和接口都允许类设计器分离类型声明和实现。给定的接口可由任何类或结构继承和实现;

可以为任何类中的方法创建委托,前提是该方法符合委托的方法签名。接口引用或委托可由不了解实现该接口或委托方法的类的对象使用。

分析下面例子:首先对于一个热水器对象来说,他满足一定条件的时候需要触发一个事件(委托),但这个事件不那么确定或者不只调用一个方法。

那么我们就在这个对象中声明一个委托方法:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 namespace Delegate
 5 {
 6     // 热水器
 7     public class Heater
 8     {
 9         private int temperature;
10         public delegate void BoilHandler(int param); //声明委托
11         public event BoilHandler BoilEvent; //声明事件
12         // 烧水
13         public void BoilWater()
14         {
15             for (int i = 0; i <= 100; i++)
16             {
17                 temperature = i;
18                 if (temperature > 95)
19                 {
20                     if (BoilEvent != null)
21                     { //如果有对象注册
22                         BoilEvent(temperature); //调用所有注册对象的方法
23                     }
24                 }
25             }
26         }
27     }
28 }

然后,再定义处理这个事件的一些方法:

1 // 警报器
2 public class Alarm
3 {
4     public void MakeAlert(int param)
5     {
6         Console.WriteLine("Alarm:嘀嘀嘀,水已经 {0} 度了:", param);
7     }
8 }
1 // 显示器
2 public class Display
3 {
4     public static void ShowMsg(int param)
5     { //静态方法
6         Console.WriteLine("Display:水快烧开了,当前温度:{0}度。", param);
7     }
8 }

好了,一切准备好,我们利用注册事件,调用这些委托的方法:

 1 class Program
 2 {
 3     static void Main()
 4     {
 5         Heater heater = new Heater();
 6         Alarm alarm = new Alarm();
 7         heater.BoilEvent += alarm.MakeAlert; //注册方法
 8         heater.BoilEvent += (new Alarm()).MakeAlert; //给匿名对象注册方法
 9         heater.BoilEvent += Display.ShowMsg; //注册静态方法
10         heater.BoilWater(); //烧水,会自动调用注册过对象的方法
11     }
12 }

输出为:

Alarm:嘀嘀嘀,水已经 96 度了:

Alarm:嘀嘀嘀,水已经 96 度了:

Display:水快烧开了,当前温度:96度。