创建一个应用台控制应用程序,假设设计一个高档热水器,当通电加热到时温度超过96时,扬声器发出声音告诉用户谁的温度,液晶屏显示水温的变化踢死水快开了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//定义和使用事件的步骤:
//1.在一个类中声明关于事件的委托
//public delegate 事件类型名称
//2.在类中声明事件,使用步骤1中的delegate作为事件的类型
//public event 事件类型名称 事件名称
//3.在需要引发事件的方法中编写引发事件的方法
//if(事件名称!=null) 事件名称 (this.new EventArgs())
//订阅时间,当时间发生时通知订户
//带有事件的类实例.事件名称+= new 事件名称(事件处理方法名称)
//5.编写事件处理方法
//public void 事件处理方法名称(object sender,EventArgs e)
//{
// 添加你的代码
//}
namespace HeaterEvent
{
public class Heater
{
private int temperature;
public delegate void BoilHandler(int param);//事件的委托
public event BoilHandler BoilEvent;//事件
public void BoilWater()
{
for(int i = 0; i <= 100; i++)
{
temperature = i;
if(temperature>96)
{
if(BoilEvent!=null)
{
BoilEvent(temperature);//引发事件
}
}
}
}
}
public class Alarm
{
public void MakeAlert(int param)
{
Console.WriteLine("Alarm:嘀嘀嘀,水已经{0}度了", param);
}
}
public class Display
{
public static void ShowMsg(int param)
{
Console.WriteLine("Display:水快烧开了,当前温度:", param);
}
}
class Program
{
static void Main(string[] args)
{
Heater ht = new Heater();
Alarm al = new Alarm();
ht.BoilEvent += al.MakeAlert;//给alarm的makealert方法订阅事件
ht.BoilEvent += Display.ShowMsg;//订阅静态方法
ht.BoilWater();//烧水,会自动调用订阅过的对象方法
Console.ReadKey();
}
}
}