首页 > 代码库 > c#事件机制
c#事件机制
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(); } }}
c#事件机制
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。