日期:2009-04-13  浏览次数:20474 次

第十一章 多事件示例[一个男人和三个女人的故事]

摘要:

应用FCL中的System.ComponentModel.EventHandlerList示例一个类型中发布多事件的应用




场景:一个男生有三个女朋友,各自有不同的爱好,女朋友A爱好音乐,女朋友B爱好美食,女朋友C爱好XXX,为满足各个女朋友,此男生必须进行唱歌、烹饪食物、xxx。

以此制作程序演示单类型多事件的应用,并假设此男同时只能干一件事情(即排除一边xxx一边唱歌或一边xxx一边烹饪的可能J)

如下为源代码:

using System;

using System.ComponentModel;



//男朋友的源代码

public class BoyFriend

{

protected EventHandlerList eventList

= new EventHandlerList();



//

//满足女朋友A定义音乐喜好

//使用自定义的音乐事件及回调函数

protected static readonly object musicEventKey = new object();

public class MusicEventArgs : EventArgs

{

private string strMusicName;



public string MusicName

{

get{

return strMusicName;

}

}



public MusicEventArgs(string strMusicName)

{

this.strMusicName = strMusicName;

}

}



public delegate void MusicEventHandler(object sender, MusicEventArgs args);



public event MusicEventHandler MusicMsg

{

add

{

eventList.AddHandler(musicEventKey, value);

}

remove

{

eventList.RemoveHandler(musicEventKey, value);

}

}



protected virtual void OnMusic(MusicEventArgs e)

{

Delegate d = eventList[musicEventKey];

if(d != null)

{

d.DynamicInvoke(new Object[]{this, e});

}

}



public void SimulateMusic(string strName)

{

Console.WriteLine("男朋友:好的,我给你唱支{0}吧!", strName);

OnMusic(new MusicEventArgs(strName));

}



//

//满足女朋友B的美食欲望

//

protected static readonly object cateEventKey = new object();

public class CateEventArgs : EventArgs

{

private string strCateName;

public string CateName

{

get

{

return strCateName;

}

}



public CateEventArgs(string strCateName)

{

this.strCateName = strCateName;

}

}

public delegate void CateEventHandler(Object sender, CateEventArgs args);

public event CateEventHandler CateMsg

{

add

{

eventList.AddHandler(cateEventKey, value);

}



remove

{

eventList.RemoveHandler(cateEventKey, value);