快速理解C#委托和事件之间关系的伪代码

下面这段有关讲解委托和事件的代码是伪代码,很形象地讲解了委托和事件之间的关系,对新手理解很有帮助,值得收藏。

 

using System;

using System.Collections.Generic;

using System.Text;

namespace ConsoleApplication7

{

    delegate void 事件处理格式1();

    delegate void 事件处理格式2(int n);

   

    class 遥控器  //事件引发者

    {

        public event 事件处理格式1 事件之按下开键; //遥控器上的开关

        public event 事件处理格式1 事件之按下关键;

        public event 事件处理格式2 事件之按下数字键;//遥控器上的选台键

        public  void 开机()

        {

            if (事件之按下开键 != null)

                事件之按下开键();

            //如果事件有响应者,发送事件给响应者

        }

 

        public void 关机()

        {

            if(事件之按下关键 != null)

                事件之按下关键();

        }

        public void 选台(int 频道)

        {

            if (事件之按下数字键 != null)

                事件之按下数字键(频道);

        }

    }

 

    class 电视机 //事件响应者

    {

        public  void 开机()

        {

            Console.WriteLine("屏幕亮了");

        }

        public void 关机()

        {

            Console.WriteLine("屏幕熄了");

        }

        public void 转换频道(int n)

        {

            Console.WriteLine("频道{0}播放",n);

        }

    }

   

    class 程序运行环境   //用于触发事件

    {

        static void Main(string[] args)

        {           

            遥控器 我的遥控器 = new 遥控器();

            电视机 我的电视机 = new 电视机();

            //关联"引发者""响应者"

            我的遥控器.事件之按下开键 += new 事件处理格式1(我的电视机.开机);

            我的遥控器.事件之按下关键 += new 事件处理格式1(我的电视机.关机);

            我的遥控器.事件之按下数字键 += new 事件处理格式2(我的电视机.转换频道);

 

            //开始触发事件了

            我的遥控器.开机();

            我的遥控器.选台(20);

            我的遥控器.选台(10);

            我的遥控器.选台(5);

            我的遥控器.关机();

        }

    }  

}

 

 

本文来自: IT知道网(http://www.itwis.com) 详细出处参考:http://www.itwis.com/html/net/c/20081114/2809.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值