关于C#的委托与事件的一个小DEMO

从学习.NET到现在,也有快4年时间了,一切都是在不经意间忽略,写了几年的代码,委托与事件其实一直在用,可以真的有人让我为一个类写一个事件,我真的会犹豫一下要如何写。

以下是我写的一个小DEMO。

设定一个闹钟。

namespace ConsoleApplication6
{
    public delegate void BellEventHandler(object sender, BellEventArgs e);
    public class BellEventArgs : EventArgs
    {
        public readonly int h;
        public readonly int m;
        public readonly int s;
        public BellEventArgs(int h, int m, int s)
        {
            this.h = h;
            this.m = m;
            this.s = s;
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            NaoZhong t = new NaoZhong();
            t.SetBellTime(13400);
            t.Bell += new BellEventHandler(t_Bell);
            t.StartBell();
        }
        static void t_Bell(object sender, BellEventArgs e)
        {
            Console.Write("{0}:{1}:{2}了,懒猪起床了", e.h.ToString(), e.m.ToString(), e.s.ToString());
            Console.Read();
        }

    }
    public class NaoZhong
    {
        private int Hours = 0;
        private int Minutes = 0;
        private int Seconds = 0;

        public event BellEventHandler Bell;

        public void StartBell()
        {
            while (!(DateTime.Now.Hour == Hours && DateTime.Now.Minute == Minutes && DateTime.Now.Second == Seconds))
            {


            }
            BellEventArgs e = new BellEventArgs(Hours, Minutes, Seconds);
            Bell(this, e);
        }
        public bool SetBellTime(int _h, int _m, int _s)
        {
            if (_h > 24)
            {
                return false;
            }
            if (_m > 60)
            {
                return false;
            }
            if (_s > 60)
            {
                return false;
            }
            Hours = _h;
            Minutes = _m;
            Seconds = _s;
            return true;
        }

    }

}

 学习委托与事件

 

posted @ 2012-07-26 13:53  ML Guo  阅读(325)  评论(1编辑  收藏  举报