posts - 77, comments - 54, trackbacks - 0, articles - 0
  IT博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

关于事件和委托理解3

Posted on 2006-05-31 14:19 东人EP 阅读(148) 评论(0)  编辑 收藏 引用 所属分类: .NET
范例 Events:
说明 示范实现事件处理程序,模拟汽车速度限制的控制程序,当输入的车速大于60,则触发控制事件,警告车速过快,并且要求降低车速。
 1using System;
 2
 3namespace Events
 4{
 5    /// <summary>
 6    /// Class1 的摘要说明。
 7    /// </summary>

 8    class Events
 9    {
10        /// <summary>
11        /// 应用程序的主入口点。
12        /// </summary>

13        [STAThread]
14        static void Main(string[] args)
15        {
16            long speed;
17            CheckSpeed myCheckSpeed = new CheckSpeed();
18            DoSomeThing myDoSomeThing = new DoSomeThing();
19            Console.Write("目前行车速度:");
20            speed = long.Parse(Console.ReadLine());
21            Console.WriteLine("");
22            myCheckSpeed.myEvent += new SpeedCheckHandler(myDoSomeThing.SlowDown);
23            myCheckSpeed.CheckSpeedLimit(speed);
24            Console.ReadLine();
25        }

26    }

27
28    public class SpeedCheckEventArgs : EventArgs
29    {
30        private long speed;
31        public SpeedCheckEventArgs(long speed)
32        {
33            this.speed = speed;
34        }

35        public long getSpeed
36        {
37            get
38            {
39                return speed;
40            }

41        }

42        public string WarningMessage
43        {
44            get
45            {
46                return "警告:行车超过速度界限!!";
47            }

48        }

49    }

50
51    public delegate void SpeedCheckHandler(object sender, SpeedCheckEventArgs e);
52
53    public class CheckSpeed
54    {
55        public event SpeedCheckHandler myEvent;
56        public void CheckSpeedLimit(long speed)
57        {
58            if (speed > 60)
59            {
60                SpeedCheckEventArgs speedsArgs = new SpeedCheckEventArgs(speed);
61                myEvent(this, speedsArgs);
62            }

63            else
64            {
65                Console.WriteLine("您目前的速度正常");
66            }

67        }

68    }

69
70    public class DoSomeThing
71    {
72        public void SlowDown(object sender, SpeedCheckEventArgs e)
73        {
74            Console.WriteLine(e.WarningMessage);
75            Console.WriteLine("您目前车速{0}已超速,请踩下刹车,降低速度,避免危险!!", e.getSpeed);
76            Console.WriteLine("正常行车速度请降至60KM/H以下!!");
77        }

78    }

79}

80
只有注册用户登录后才能发表评论。