事件的使用 代码示例
?
摘自:C#程序设计教程 朱毅华 第134页
?
using System;
using System.Collections.Generic;
using System.Text;
namespace t_Event
{
??? //--定义事件包含数据
??? class MyEventArgs : EventArgs
??? {
??????? private string strText;
??????? public MyEventArgs(string StrText)? //--构造函数
??????? {
??????????? this.strText = StrText;
??????? }
??????? public string StrText
??????? {
??????????? get { return strText; }
??????????? set { strText = value; }
??????? }
??? }
??? //--发布事件的类
??? class EventSource
??? {
??????? MyEventArgs EvArgs = new MyEventArgs("发布事件");
??????? //定义委托
??????? public delegate void EventHandler(object from, MyEventArgs e);
??????? //定义事件
??????? public event EventHandler TextOut;
??????? //--激活事件的方法
??????? public void TriggerEvent()
??????? {
??????????? if (TextOut != null)? //--不为空,表示有用户订阅
??????????? {
??????????????? TextOut(this, EvArgs);
??????????? }
??????? }
?
??? }
??? //--订阅事件的类
??? class TestApp
??? {
??????? //--处理事件的静态方法
??????? public static void CatchEvent(object from, MyEventArgs e)
??????? {
??????????? Console.WriteLine("调用方法CatchEvent");
??????????? Console.WriteLine("CatchEvent:{0}",e.StrText);
??????? }
??????? //处理事件的方法
??????? public void InstanceCatch(object from, MyEventArgs e)
??????? {
??????????? Console.WriteLine("调用方法InstanceCatch");
??????????? Console.WriteLine("InstanceEvent:{0}", e.StrText);
??????? }
??????? static void Main(string[] args)
??????? {
??????????? EventSource evsrc = new EventSource();
??????????? //订阅事件
??????????? evsrc.TextOut += new EventSource.EventHandler(CatchEvent);
??????????? evsrc.TriggerEvent();
??????????? Console.WriteLine("1 -------------------------");
??????????? //取消事件
??????????? evsrc.TextOut -= new EventSource.EventHandler(CatchEvent);
??????????? evsrc.TriggerEvent();
??????????? Console.WriteLine("取消事件后,这次什么都没做");
??????????? Console.WriteLine("2 -------------------------");
??????????? TestApp theApp = new TestApp();
??????????? evsrc.TextOut += new EventSource.EventHandler(theApp.InstanceCatch);
??????????? evsrc.TriggerEvent();
??????????? Console.WriteLine("3 -------------------------");
??????????? Console.ReadKey();
???????
??????? }
??? }
}