using System;
using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication8
{class Program
{ static void Main(string[] args) {//第三步:定义对象并添加事件
Priter priter = new Priter(); priter.OnPrintComplete += new EventHandler<PrintCompleteEventArgs>(priter_OnPrintComplete); for (int i = 0; i < 500; i++) {//第四步:执行实际方法
priter.Print(i); System.Threading.Thread.Sleep(100); } }static void priter_OnPrintComplete(object sender, PrintCompleteEventArgs e)
{//第五步:处理回调函数
Console.WriteLine("完成打印:" + e.message); if (e.message % 10 == 0) Console.WriteLine("我是10的倍数," + e.message); } }/// <summary>
/// 第二步:定义事件类 /// </summary> public class Priter { /// <summary> /// 用event关键字声明事件对象(如果EventHandler不够用,可先用delegate定义一个处理事件) /// </summary> public event EventHandler<PrintCompleteEventArgs> OnPrintComplete;/// <summary>
/// 实际打印方法 /// </summary> /// <param name="data"></param> public void Print(int data) { //在这里执行打印操作.. //TO DO.. //.. Console.WriteLine("开始打印:"+data);//执行完后通知执行外部的事件方法(如果是异步操作,可另外开一线程监听然后执行以下通知)
OnPrintComplete(this, new PrintCompleteEventArgs(data)); } }/// <summary>
/// 第一步:定义事件参数类 /// </summary> public class PrintCompleteEventArgs : EventArgs { public int message; public PrintCompleteEventArgs(int Message) { this.message = Message; } }}--------------------------------------------------------------------------
namespace 事件{ //发布事件的类 public class TestEventSource { //定义事件参数类 public class TestEventArgs : EventArgs { public readonly char KeyToRaiseEvent; public TestEventArgs(char keyToRaiseEvent) { KeyToRaiseEvent = keyToRaiseEvent; } }//定义delegate
public delegate void TestEventHandler(object sender, TestEventArgs e); //用event 关键字声明事件对象 public event TestEventHandler TestEvent;//事件触发方法
protected virtual void OnTestEvent(TestEventArgs e) { if (TestEvent != null) TestEvent(this, e); }//引发事件
public void RaiseEvent(char keyToRaiseEvent) { TestEventArgs e = new TestEventArgs(keyToRaiseEvent); OnTestEvent(e); }}
//监听事件的类 public class TestEventListener { //定义处理事件的方法,他与声明事件的delegate具有相同的参数和返回值类型 public void KeyPressed(object sender, TestEventSource.TestEventArgs e) { Console.WriteLine("发送者:{0},所按得健为:{1}", sender, e.KeyToRaiseEvent); }//订阅事件
public void Subscribe(TestEventSource evenSource) { evenSource.TestEvent += new TestEventSource.TestEventHandler(KeyPressed); } //取消订阅事件 public void UnSubscribe(TestEventSource evenSource) { evenSource.TestEvent -= new TestEventSource.TestEventHandler(KeyPressed); } }//测试类
public class Test { public static void Main() { //创建事件源对象 TestEventSource es = new TestEventSource(); //创建监听对象 TestEventListener el = new TestEventListener(); //订阅事件 Console.WriteLine("订阅事件\n"); el.Subscribe(es); //引发事件 Console.WriteLine("输入一个字符,再按enter键"); string s = Console.ReadLine(); es.RaiseEvent(s.ToCharArray()[0]); //取消订阅事件 Console.WriteLine("\n取消订阅事件\n"); el.UnSubscribe(es);//引发事件
Console.WriteLine("输入一个字符,再按enter健"); s = Console.ReadLine(); es.RaiseEvent(s.ToCharArray()[0]);
}
}}