C# 中的委托和事件

MyClass.cs


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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值