首页 > 代码库 > C# 事件
C# 事件
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; //定义临时的委托 if (handler != null) { handler(this, e); } } protected virtual void OnPubLife(PubEventArgs e) { PubLifeEventHandler handler = PubLife; if (handler != null) { handler(this, e); } } public void issueComputer(string magezineName,DateTime pubDate) { Console.WriteLine(pubDate.ToShortDateString() + "发行了" + magezineName); OnPubComputer(new PubEventArgs(magezineName, pubDate)); //这里调用保护的虚拟方法。 } public void issueLife(string magezineName, DateTime pubDate) { Console.WriteLine(pubDate.ToShortDateString() + "发行了" + magezineName); OnPubLife(new PubEventArgs(magezineName, pubDate)); } } class Pubscriber //订阅者 { private string name; public Pubscriber(string name) { this.name = name; } public void Receive(object sender, PubEventArgs e) { Console.WriteLine("{0} {1} 已经收到{2}", e.pubDate.ToString(), name, e.magazineName); } } class Program { static void Main(string[] args) { Publisher pub = new Publisher(); Pubscriber zs = new Pubscriber("张三"); pub.PubComputer += new Publisher.PubComputerEventHandler(zs.Receive); //添加事件 用户张三订阅电脑杂志 Pubscriber ls = new Pubscriber("李四"); pub.PubComputer += new Publisher.PubComputerEventHandler(ls.Receive); //添加事件 用户李四订阅电脑杂志 pub.PubLife += new Publisher.PubLifeEventHandler(ls.Receive); //添加事件 用户李四订阅生活杂志 pub.issueComputer("电脑杂志",Convert.ToDateTime("2014-01-01")); pub.issueLife("生活杂志",Convert.ToDateTime("2014-01-01")); Console.WriteLine(); Console.WriteLine("一年后。。。"); pub.PubComputer -= new Publisher.PubComputerEventHandler(ls.Receive); //移除事件 用户李四取消订阅电脑杂志 pub.issueComputer("电脑杂志", Convert.ToDateTime("2014-02-01")); pub.issueLife("生活杂志", Convert.ToDateTime("2014-02-01")); Console.ReadKey(); } }
C# 事件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。