委托事件
class MailManager
{
//传递给事件接受者的类型定义信息
public class MailMsgEventAgs : EventArgs
{
public readonly String from, to, subject, body;
public MailMsgEventAgs(String from, String to, String subject, String body)
{
this.from = from;
this.to = to;
this.subject = subject;
this.body = body;
}
}
//委托类型定义了接受者必须实现的回调方法原型
public delegate void MailMsgEventHandle(object sender, MailMsgEventAgs args);
#region 我这里是用显示控制事件注册
//显示定义一个私有委托链表的字段
private MailMsgEventHandle mailMsgEventHandlerDelegate;
//显示定义事件及访问器方法
public event MailMsgEventHandle MailMsg
{
//将传入的事件处理器(value)添加到委托链表上
add
{
mailMsgEventHandlerDelegate = (MailMsgEventHandle)Delegate.Combine(mailMsgEventHandlerDelegate, value);
}
//将传人的事件处理器(value)从委托链表上移除
remove
{
mailMsgEventHandlerDelegate = (MailMsgEventHandle)Delegate.Remove(mailMsgEventHandlerDelegate, value);
}
}
#endregion
//受保护的虚函数负责通知事件的登记对象
protected virtual void OnMailMsg(MailMsgEventAgs e)
{
//有对象登记吗
if (mailMsgEventHandlerDelegate != null)
{
//如果有,这通知委托链表上的所有对象
mailMsgEventHandlerDelegate(this, e);
}
}
//将输入转化为期望的事件,通知委托链表上的所有对象
public void SimulateArrivingMsg(string from, String to, String subject, String body)
{
MailMsgEventAgs e = new MailMsgEventAgs(from, to, subject, body);
OnMailMsg(e);
}
}
上面显示控制事件的注册可以用定义一个事件成员取代public event MailMsgEventHandle MailMsg;
可是显示控制事件的注册有个好处,如果你是频繁的添加或移除委托实例,同时我们的应用程序是在单线程环境下运行,这时在对委托实例的对象进行同步的访问就会损伤性能
class Fax {
public Fax(MailManager mm)
{
//委托实例
mm.MailMsg += new MailManager.MailMsgEventHandle(mm_MailMsg);
}
void mm_MailMsg(object sender,MailManager.MailMsgEventAgs args)
{
Console.WriteLine("Faxing mail message:");
Console.WriteLine("from:{0}\n To :{1}\n Subject:{2}\n Body:{3}\n", args.from, args.to, args.subject, args.body);
}
}
MailManager me1 = new MailManager();
Fax me = new Fax(me1);
me1.SimulateArrivingMsg("gu", "bao", "aa", "bb");