C#事件与委托简单实现

来源:互联网 发布:qt高级编程 pdf 编辑:程序博客网 时间:2024/06/07 12:07

假设我们有个高档的热水器(Heater),我们给它通上电,当水温超过95度的时候:1、扬声器(Alarm)会开始发出语音,告诉你水的温度;2、液晶屏(Display)也会改变水温的显示,来提示水已经快烧开了。

可以建立如下事件与委托(在控制台下实现):

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();        }    }}


原创粉丝点击