namespace test { class Publisher//出版社 { public delegate void PubComputer(string magazineName);//声明事件所需的代理 public delegate void PubLife(string magazineName); public event PubComputer OnPubComputer;//事件的声明 事件的本质是一个委托链 public event PubLife OnPubLife; public void issueComputer()//触发事件的方法 { if (OnPubComputer != null){ Console.WriteLine("发行电脑刊物"); OnPubComputer("编程指南"); } } public void issueLife() { if (OnPubLife!=null) { Console.WriteLine("发行生活刊物"); OnPubLife("家具"); } } } class Subsriber//订阅者 { private string name; public Subsriber(string name){ this.name = name; } public void Receive(string magazineName)//在事件订阅者中定义事件处理程序 { Console.WriteLine(name + "已经收到" + magazineName); } } class Story { static void Main() { Publisher pub = new Publisher(); Subsriber zs = new Subsriber("张三"); pub.OnPubComputer += new Publisher.PubComputer(zs.Receive);//向事件发行者订阅一个事件 Subsriber ls = new Subsriber("李四"); pub.OnPubComputer += new Publisher.PubComputer(ls.Receive); pub.OnPubLife += new Publisher.PubLife(ls.Receive); pub.issueComputer();//触发事件 pub.issueLife(); Console.WriteLine(); Console.WriteLine("一年后"); pub.OnPubComputer -= new Publisher.PubComputer(ls.Receive); pub.issueComputer();//触发事件 pub.issueLife(); } } }
时间: 2024-10-17 07:55:41