C#事件与委托(水壶烧水事件)
来源:互联网 发布:重庆市网络知识竞赛 编辑:程序博客网 时间:2024/04/29 00:23
假设我们有个高档的热水器,我们给它通上电,当水温超过95度的时候:
1、扬声器会开始发出语音,告诉你水的温度
2、液晶屏也会改变水温的显示,来提示水已经快烧开了。
对上面的程序做个改进:
假设热水器由三部分组成:
热水器,仅仅负责烧水
警报器,发出警报
显示器,显示提示和水温
代码:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace task3{ public delegate void MyAlarm(int temperature); //创建委托报警 public delegate void MyDispaly(int temperature); //创建委托显示 class Heater //热水器类 { private int temperature; //温度 public int Temperature { get { return temperature; } set { if ((temperature >= 0) && (temperature <= 100)) temperature = value; else Console.WriteLine("温度有问题!显示出错!"); } } public event MyAlarm DoMyAlarm; //建立事件报警 public event MyDispaly DoMyDisplay; //建立事件显示 public void BoilWater(int m) //m 表示烧水时间,没分钟提高摄氏度 { Console.WriteLine("感谢您使用热水器,现在温度为{0},\n本次烧水时间为{1}分钟。" + "(每分钟提高10摄氏度)", this.temperature, m); this.temperature = m * 10 + this.temperature; if (this.temperature >= 100) this.temperature = 100; if (this.temperature >= 95) { DoMyAlarm(this.temperature); DoMyDisplay(this.temperature); Console.WriteLine(""); } else Console.WriteLine("目前还没烧开!\n"); } } class Alarm //报警器类 { public void MakeAlert(int temperature) { Console.WriteLine("叮叮叮,叮叮叮。。。\n报警器提示水壶水温现在是{0}",temperature); } } class Display //显示器类 { public void ShowMsg(int temperature) { Console.WriteLine("显示器提示现在的水温为{0}", temperature); } } class Program { static void Main(string[] args) { Heater he1 = new Heater(); //第一次烧水(水伟烧开,不会触发事件) he1.Temperature = 10; Alarm al1 = new Alarm(); Display di1 = new Display(); he1.DoMyAlarm += al1.MakeAlert; //建立关联 he1.DoMyDisplay += di1.ShowMsg; //建立关联 he1.BoilWater(1); Heater he2 = new Heater(); //第二次烧水(水烧开,触发显示与报警事件) he2.Temperature = 10; Alarm al2 = new Alarm(); Display di2 = new Display(); he2.DoMyAlarm += al2.MakeAlert; //建立关联 he2.DoMyDisplay += di2.ShowMsg; //建立关联 he2.BoilWater(10); Console.Read(); } }}
运行截图:
阅读全文
0 0
- C#事件与委托(水壶烧水事件)
- C#委托、事件学习之(三)——热水器烧水案例
- c# 委托与事件
- C#委托与事件
- C# 委托与事件
- c#委托与事件
- C# - 委托与事件
- C#委托与事件
- C# 委托与事件
- C#委托与事件
- c#委托与事件
- C#事件与委托
- C# 事件与委托
- C#事件与委托
- c#委托与事件
- C#委托与事件
- c#委托与事件
- C#委托与事件
- [leetcode]解决Clone Graph的一点小心得
- 特手天气
- [设计模式]观察者模式
- Python 每日记录
- 拨钟问题
- C#事件与委托(水壶烧水事件)
- 大端与小端
- C语言_我的初成长
- 上传笔记【一】webUploader 多文件上传并保存数据库
- bzoj 2823(计算几何+最小覆盖圆)
- 记录采用cloudera-manager安装CDH集群的过程
- bzoj3048 [Usaco2013 Jan]Cow Lineup
- 听到别人发论文的感想
- openSUSE+Windows10(VirutalBox)