说明(2017-6-14 15:04:13):
1. 热水器案例,为了便于理解,采用了蹩脚但直观的英文命名,哼哼。
heater类,加热,声明一个委托,定义一个委托事件:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _12事件 { public delegate void MyDel(int temp); class Heater { public event MyDel del; private int temp; public int Temp { get { return temp; } set { temp = value; } } public void Heat() { for (int i = 0; i < 100; i++) { temp = i; if (temp > 95) { if (del != null) { del(temp); } } } } } }
Alarmer类,警报:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _12事件 { class Alarmer { public void Alarm(int temp) { Console.WriteLine("滴滴滴,报警!!水已经{0}度了", temp); } } }
ShowTemper,显示器类:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _12事件 { class ShowTemper { public void ShowTemp(int temp) { Console.WriteLine("屏幕显示:当前温度{0}度", temp); } } }
main函数,委托绑定警报和显示两个方法:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _12事件 { class Program { static void Main(string[] args) { Heater heater = new Heater(); Alarmer alarmer = new Alarmer(); ShowTemper showtemper = new ShowTemper(); heater.del += alarmer.Alarm; heater.del += showtemper.ShowTemp; heater.Heat(); //heater.del(heater.Temp); Console.ReadKey(); } } }
参考资料:
http://www.tracefact.net/CSharp-Programming/Delegates-and-Events-in-CSharp.aspx