新手提问(关于事件)
程序代码:
class PubEventArgs : EventArgs { private readonly string m_magazineName; private readonly DateTime m_pubDate; public PubEventArgs(string magazineName, DateTime pubDate) { m_magazineName = magazineName; m_pubDate = pubDate; } public string MagazineName { get { return m_magazineName; } } public DateTime PubDate { get { return m_pubDate; } } } class Publisher //出版者 { public delegate void PubComputerEventHandler(object sender,PubEventArgs e);//声明事件所需的代理 public delegate void PubLifeEventHandler(object sender, PubEventArgs e); public event PubComputerEventHandler PubComputer;//事件的声明 public event PubLifeEventHandler PubLife; protected virtual void OnPubComputer(PubEventArgs e) { PubComputerEventHandler handler = PubComputer; // 疑问1 if (handler != null) { handler(this,e); // 疑问2 } } protected virtual void OnPubLife(PubEventArgs e) { PubLifeEventHandler handler = PubLife; if (handler != null) { handler(this, e); } } public void issueComputer(string magazinName,DateTime pubDate) //触发事件的方法 { Console.WriteLine("发行"+magazinName); OnPubComputer(new PubEventArgs(magazinName, pubDate)); } public void issueLife(string magazinName, DateTime pubDate) { Console.WriteLine("发行" + magazinName); OnPubLife(new PubEventArgs(magazinName, pubDate)); } } class Subscriber //订阅者 { private string name; public Subscriber(string name) { this.name = name; } public void Receive(object sender,PubEventArgs e) //在事件订阅者中定义事件处理程序 { Console.WriteLine(e.PubDate+" "+name+"已经收到了"+e.MagazineName); } } class Program { static void Main(string[] args) { Publisher Pub = new Publisher(); Subscriber zs = new Subscriber("张三"); Subscriber ls = new Subscriber("李四"); Pub.PubComputer += new Publisher.PubComputerEventHandler(zs.Receive); //向事件发行者订阅一个事件 Pub.PubComputer += new Publisher.PubComputerEventHandler(ls.Receive); Pub.PubLife += new Publisher.PubLifeEventHandler(ls.Receive); Pub.issueComputer("电脑杂志",Convert.ToDateTime("2006-1-1")); Pub.issueLife("生活杂志",Convert.ToDateTime("2006-6-1")); Console.WriteLine(); Console.WriteLine("一年后!"); Pub.PubComputer -= new Publisher.PubComputerEventHandler(ls.Receive); Pub.issueComputer("电脑杂志", Convert.ToDateTime("2007-1-1")); Pub.issueLife("生活杂志", Convert.ToDateTime("2007-6-1")); Console.ReadKey(); } } 疑问1:.PubComputerEventHandler handler = PubComputer; handler是一个委托类型,PubComputer是声明的一个事件,这句话代表什么意思呢? 2.handler(this,e); 这句话就彻底不理解了。 还望高手们不吝赐教,指点一下我们这些初学者。
[ 本帖最后由 乱舞春秋 于 2011-10-11 22:04 编辑 ]