您的位置:首页 > 编程语言 > C#

C#事件与委托简单实现

2013-10-10 19:04 337 查看
假设我们有个高档的热水器(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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  事件 控制台 委托