码迷,mamicode.com
首页 > Windows程序 > 详细

c#事件机制

时间:2016-12-28 01:15:16      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:iss   事件机制   put   test   receive   sub   程序   oid   compute   

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#事件机制

标签:iss   事件机制   put   test   receive   sub   程序   oid   compute   

原文地址:http://www.cnblogs.com/as3lib/p/6227703.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!