关于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;
        }

    }

}

 学习委托与事件

 

转载于:https://www.cnblogs.com/guolihao/archive/2012/07/26/2609944.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值