MyClass.cs
MainClass.cs
参考[url]http://blog.youkuaiyun.com/delicacylee/archive/2008/03/02/2139928.aspx[/url]
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
//声明一个delegate
public delegate void EventHandler(string input);
/// <summary>
/// 测试C#的event机制
/// </summary>
public class MyClass
{
//声明一个成员变量来保存事件句柄(事件被激发时被调用的delegate)
private EventHandler m_Handler = null;
//激发事件
public void FireAEvent(string input)
{
if (m_Handler != null)
{
m_Handler(input);
}
}
//声明事件
public event EventHandler AEvent
{
add//添加访问器
{
//注意,访问器中实际包含了一个名为value的隐含参数
//该参数的值即为客户程序调用+=时传递过来的delegate
Console.WriteLine("AEvent add被调用,value的HashCode为:" + value.GetHashCode());
if (value != null) ...{ m_Handler = value; };//设置m_Handler域保存新的handler
}
remove//删除访问器
{
Console.WriteLine("AEvent remove被调用,value的HashCode为:" + value.GetHashCode());
if (value != null) ...{ m_Handler = null; };//置m_Handler为null,该事件将不再被激发
}
}
public MyClass()
{
//TODO
}
}
}
MainClass.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class MainClass
{
[STAThread]
static void Main(string[] args)
{
//实例化一个MyClass的对象Obj
MyClass Obj = new MyClass();
//基于MyEventHandler()函数定义一个EventHandler
EventHandler MyHandler = new EventHandler(MyEventHandler);
Console.WriteLine("MyHandler的HashCode为:" + MyHandler.GetHashCode());
Console.WriteLine();
//预定事件
Console.WriteLine("Obj.AEvent += MyHandler被调用");
Obj.AEvent += MyHandler;
//激发事件
Console.WriteLine("Main函数激发Obj的AEvent事件!");
Obj.FireAEvent("aaa");
//撤销事件
Console.WriteLine("Obj.AEvent -= MyHandler被调用");
Obj.AEvent -= MyHandler;
Console.WriteLine();
//再次试图激发事件
Console.WriteLine("Main函数试图在撤消事件后激发Obj的AEvent事件!");
Obj.FireAEvent("aaaa");
Console.WriteLine("---程序运行完毕---");
Console.ReadLine();
}
//真正的事件处理函数
static void MyEventHandler(string input)
{
Console.WriteLine("This is Event!");
}
}
}
参考[url]http://blog.youkuaiyun.com/delicacylee/archive/2008/03/02/2139928.aspx[/url]