C# 中事件
2013-11-06 13:00
267 查看
C#中使用事件需要的步骤:
创建一个委托
将创建的委托与特定事件关联(.Net类库中的很多事件都是已经定制好的,所以他们也就有相应的一个委托,在编写关联
事件处理程序--也就是当有事件发生时我们要执行的方法的时候我们需要和这个委托有相同的签名)
编写事件处理程序
利用编写的事件处理程序生成一个委托实例
把这个委托实例添加到产生事件对象的事件列表中去,这个过程又叫订阅事件
创建一个委托
将创建的委托与特定事件关联(.Net类库中的很多事件都是已经定制好的,所以他们也就有相应的一个委托,在编写关联
事件处理程序--也就是当有事件发生时我们要执行的方法的时候我们需要和这个委托有相同的签名)
编写事件处理程序
利用编写的事件处理程序生成一个委托实例
把这个委托实例添加到产生事件对象的事件列表中去,这个过程又叫订阅事件
using System; using System.Collections.Generic; using System.Linq; using System.Text; 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(); //烧水,会自动调用注册过对象的方法 Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Text; public delegate void addeventhandler(object sender,EventArgs e);//声明一个事件委托类型 public class listwithevent : ArrayList { public event addeventhandler added; protected virtual void onchanged(EventArgs e) { if(added != null ) { added (this , e); } } public override int Add(object value) { int i = base.Add(value ); onchanged (EventArgs .Empty ); return i; } } class eventmethod { public void listchanged(object sender, EventArgs e) { Console.WriteLine("this is called when the event fires."); } } class program { public static void Main() { listwithevent list = new listwithevent (); eventmethod test = new eventmethod (); list.added += new addeventhandler(test .listchanged); list.Add("123456"); Console.ReadLine(); } }
相关文章推荐
- C# 浅谈委托----温故而知新
- 在C#中实现Socket端口复用
- c#添加了Configuration;后,竟然找不到 ConfigurationManager 这个类
- C#结构内存布局介绍
- C#常量(const)
- c#修改xml文件
- C#实现窗体截图(代码+效果)
- C# 下使用Google地图Demo
- C# Struct的内存布局
- C#全屏截图
- C# 中的委托和事件
- C# DateTime显示时间格式的使用
- C#按位操作,直接操作INT数据类型的某一位
- C#中堆和栈的区别分析(有待更新总结)
- C#中堆和栈的区别分析(有待更新总结2)
- c#中的属性和字段
- C# 子类实例化过程
- C# 并行 反射 去掉实体属性多余空格
- C# 白话系列之——白话委托
- C#导入Excel2010出现加载DLL失败或者类库未注册的问题,0x8002801D或者0x80029C4A