【C#】Observer设计模式委托事件的使用(获取Subject多个属性)
2015-11-12 17:19
615 查看
using System; using System.Collections.Generic; using System.Text; namespace Delegate { // 热水器 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 > 95) { 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:水快烧开了,当前温度:{0}度。", param); } } class Program { static void Main() { Heater heater = new Heater(); Alarm alarm = new Alarm(); heater.BoilEvent += alarm.MakeAlert; //注册方法 heater.BoilEvent += (new Alarm()).MakeAlert; //给匿名对象注册方法 heater.BoilEvent += Display.ShowMsg; //注册静态方法 heater.BoilWater(); //烧水,会自动调用注册过对象的方法 } } }
相关文章推荐
- C#更改系统时间
- 使用csc.exe构建C#应用程序
- C# DLL文件注册问题(涉及AxInterop.WMPLib.dll等)
- Leetcode-149-Max Ponits on a Line C#
- c# 操作excle
- c# 利用Log Parser制作简易可视化netmon抓包分析工具
- C#实现Dll(OCX)控件自动注册的两种方法(转)
- .NET根据wsdl文件解析成调用的类文件,客户端方法
- C#学习笔记 字符串和正则表达式
- C#怎样通过url调用接口
- 在C#中调用EXE文件
- 使用emguCV/C# opencv绘制自定义直方图
- (C#)多线程读取注册表,加载至TreeView
- C#TreeView复选框的选择
- C# 防止界面假死 多线程进度条的合理使用
- C#删除和清空文件夹的程序
- C#接口作用的深入理解
- Windows Emacs OmniSharp 配置.md
- C#异步调用
- 最新的c#分页办法