C#事件与委托简单实现
2013-10-10 19:04
337 查看
假设我们有个高档的热水器(Heater),我们给它通上电,当水温超过95度的时候:1、扬声器(Alarm)会开始发出语音,告诉你水的温度;2、液晶屏(Display)也会改变水温的显示,来提示水已经快烧开了。
可以建立如下事件与委托(在控制台下实现):
Heater.cs
Display.cs
Alarm.cs
Program.cs
可以建立如下事件与委托(在控制台下实现):
Heater.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { public class Heater { int temperature; public string bread = "007"; public delegate void Handle(object obj,BoiledEventArgs e); public event Handle Boiled; public class BoiledEventArgs:EventArgs { public readonly int temperature; public BoiledEventArgs(int temperature) { this.temperature = temperature; } } protected virtual void OnBoiled(BoiledEventArgs e) { if (Boiled != null) Boiled(this, e); } public void BoilWater() { for (int i = 0; i <= 100; i++) { temperature = i; if (temperature > 95) { if (Boiled != null) { BoiledEventArgs e = new BoiledEventArgs(temperature); OnBoiled(e); } } } } } }
Display.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { public class Display { public static void ShowMsg(object obj,Heater.BoiledEventArgs e) { Heater heater = (Heater)obj; Console.WriteLine("{0}:警告:水已经{1}度了!!", heater.bread, e.temperature.ToString()); } } }
Alarm.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { public class Alarm { public void MakeAlert(object obj, Heater.BoiledEventArgs e) { Heater heater = (Heater)obj; Console.WriteLine("{0}:水已经{1}度了!", heater.bread, e.temperature.ToString()); } } }
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Heater heater = new Heater(); Alarm alarm=new Alarm(); heater.Boiled += alarm.MakeAlert; heater.Boiled += Display.ShowMsg; heater.BoilWater(); Console.ReadKey(); } } }
相关文章推荐
- 用C#中的委托和事件简单实现观察者模式
- .net2005(C#)下实现事件和委托的简单示例
- C# 委托之 用委托实现事件 三枪控件
- C# 委托与事件简单应用
- C#、最简单、事件委托、订阅事件、订阅者模式
- C#里的委托和事件实现Observer(观察者)
- c# 用委托和事件实现不同窗体间的通讯
- 用 C++ 实现 C# 中的 委托/事件 (4-functor1)
- C#里的委托和事件实现Observer (转载)
- Unity3D 利用C#实现简单的代理模式Delegate(委托)
- C# 委托与事件简单应用
- C#里的委托和事件实现
- 用 C++ 实现 C# 中的 委托/事件 (5-functor2)
- C#利用事件与委托进行窗体间传值简单小例子
- C#里的委托和事件实现Observer
- c#中的委托和事件的简单实例_c#应用
- C#简单的委托与事件
- 用C++实现C#中的委托/事件(标准C++之升级版)
- C#利用lambda实现委托事件的挂接
- C#通过“委托和事件”的方式实现进程监控并与“普通方式”对比