生命如此短暂,掌握技艺却要如此长久

风流不在谈锋胜, 袖手无言味最长。**_** 莫言大道人难得,自是功夫不到头。

导航

用事件和代理实现的一个闹钟实例

网速慢又不能插入代码,只好粘贴了
using System;

namespace Clock
{
public delegate void GetupNow();
 class home
 {
  /// <summary>
  /// 闹钟实现
  /// </summary>
  
  [STAThread]
  static void Main(string[] args)
  {
   Clock clock=new Clock();
   Man man=new Man();

   GetupNow getupNow;

   getupNow=new GetupNow(man.Getup);
   clock.getup+=new GetupNow(man.Getup);

   clock.Settime();
   clock.Ifring();
   Console.ReadLine(); 
   
  }
 }
 class Clock
 {
  public System.DateTime time;
  public event GetupNow getup;

  public void Settime()
  {
   int x=0;
   Console.WriteLine(System.DateTime.Now.ToShortDateString()+"请输入你要在多少毫秒后被叫醒");
   time=new DateTime();
   time=System.DateTime.Now;
   x=int.Parse(Console.ReadLine().Trim());
   time=time.AddSeconds(x);   
  }
  public void Ifring()
  {
    do
    {
     System.Threading.Thread.Sleep(1000); //休眠1000毫秒
     Console.WriteLine(time.Second-System.DateTime.Now.Second);//输出当前时间与响铃时间的差值
    }
    while
     (time.Second>System.DateTime.Now.Second);
    Ring();
    getup();
  }
  private void Ring()
  {
   Console.WriteLine("时间到");
  }

 }
 class Man
 {
    public void Getup()
  {
   Console.WriteLine("我起床了·!·!");
  }
 }
}
简单地说就是定义要通过事件调用的函数的代理,然后再将此代理注册到其他类中的事件上,在合适的时间调用。

posted on 2006-01-12 20:09  拼命郎  阅读(491)  评论(1编辑  收藏  举报