首页 > 代码库 > 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# 事件