现在的位置: 首页 > 综合 > 正文

一个比较经典的委托与事件实例

2013年07月25日 ⁄ 综合 ⁄ 共 2494字 ⁄ 字号 评论关闭
 1class TimeInfoEventArgs:EventArgs
 2    {
 3        public readonly int hour;
 4        public readonly int minute;
 5        public readonly int second;
 6        public TimeInfoEventArgs(int hour,int minute,int second)
 7        {
 8            this.hour = hour;
 9            this.minute = minute;
10            this.second = second;
11
12        }

13    }

14
15class Clock
16    {
17        private int hour;
18        private int minute;
19        private int second;
20
21        public delegate void SecondChangedHandler(object clock,TimeInfoEventArgs timeInfomation);
22
23        public event SecondChangedHandler OnSecondChange;
24
25        public void Run()
26        {
27            for (; ; )
28            {
29                Thread.Sleep(10);
30                System.DateTime dt = System.DateTime.Now;
31                if(dt.Second!=second)
32                {
33                    TimeInfoEventArgs timeInformation = new TimeInfoEventArgs(dt.Hour, dt.Minute, dt.Second);
34
35                    if(OnSecondChange!=null)
36                    {
37                        OnSecondChange(this, timeInformation);
38                    }

39                }

40                this.second = dt.Second;
41                this.minute = dt.Minute;
42                this.hour = dt.Hour;
43            }

44        }

45    }

46 class DisplayClock
47    {
48        public void Subscribe(Clock theClock)
49        {
50            theClock.OnSecondChange+=new Clock.SecondChangedHandler(TimeHasChanged);
51           
52        }

53        public void TimeHasChanged(object theClock,TimeInfoEventArgs ti)
54        {
55            Console.WriteLine("Current Time:{0}:{1}:{2} ",ti.hour.ToString(),ti.minute.ToString(),ti.second.ToString());
56        }

57    }

58 class LogCurrentTime
59    {
60        public void subscribe(Clock theClock)
61        {
62            theClock.OnSecondChange+=new Clock.SecondChangedHandler(WriteLogEntry);
63        }

64        public void WriteLogEntry(object theClock,TimeInfoEventArgs ti)
65        {
66            Console.WriteLine("Logging to file: {0}:{1}:{2}\n",ti.hour.ToString(),ti.minute.ToString(),ti.second.ToString());
67
68        }

69    
70    }

71class Program
72    {
73        static void Main(string[] args)
74        {
75            Clock theClock = new Clock();
76            DisplayClock dc = new DisplayClock();
77            dc.Subscribe(theClock);
78            LogCurrentTime lct = new LogCurrentTime();
79            lct.subscribe(theClock);
80            theClock.Run();
81        }

82    }

抱歉!评论已关闭.