代码改变世界

委托和事件

2011-03-30 13:23  闫妍  阅读(247)  评论(0编辑  收藏  举报

通过看一个程序我们能够更加深刻的了解委托和事件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{

    public delegate void TimeDelegate(object obj, TimeEventArgs args);
   
    class Program
    {
        /// <summary>
        ///  控制台程序的起点。
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            Clock clock = new Clock(); //实例化一个时钟

            clock.TimeChanged111111 += new TimeDelegate(闫妍); //用前面声明的委托声明一个事件
            clock.go();

 

        }

        public static void 闫妍(object obj, TimeEventArgs args)
        {
            Console.WriteLine("现在的时间是:" + args.Hour + ":" + args.Minute + ":" + args.Second);
        }
    }

    /// <summary>
    /// 时间参数类
    /// </summary>
    public class TimeEventArgs : EventArgs
    {
        private int hour;
        private int minute;
        private int second;
        public TimeEventArgs(int hour, int minute, int second)
        {
            this.hour = hour;
            this.minute = minute;
            this.second = second;
        }
        public int Hour
        {
            get
            {
                return hour;
            }
        }
        public int Minute
        {
            get
            {
                return minute;
            }
        }
        public int Second
        {
            get
            {
                return second;
            }
        }
    }

 


    /// <summary>
    /// 这是一个时钟类
    /// </summary>
    class Clock
    {

        /// <summary>
        /// 用前面声明的委托去声明一个事件
        /// </summary>
        public event TimeDelegate TimeChanged111111;

        public void go()
        {
            DateTime initi = DateTime.Now;
            int h1 = initi.Hour;
            int m1 = initi.Minute;
            int s1 = initi.Second;
            while (true)
            {
                DateTime now = DateTime.Now;
                int h2 = now.Hour;
                int m2 = now.Minute;
                int s2 = now.Second;
                if (s2 != s1)
                {
                    h1 = h2;
                    m1 = m2;
                    s1 = s2;

                    TimeEventArgs args = new TimeEventArgs(h2, m2, s2);


                    TimeChanged111111(this, args);
                }
            }
        }
    }

 

 

}