C# 事件机制实例

来源:互联网 发布:天地知我心二的作品 编辑:程序博客网 时间:2024/05/16 05:17
  1. /*
  2.  * 由 SharpDevelop 创建。
  3.  * 用户: zhaojp
  4.  * 日期: 2008-12-2
  5.  * 时间: 11:12
  6.  * 照.NET FrameWork的事件设计准则去书写代码
  7. 1 事件的命名应遵循PascalCasing命名方式
  8. 2 申明delegate时使用void作为返回类型,事件接受两个传入参数一律命名为sender和e
  9. 3 定义一个事件提供数据的类对类以EventNameEventArgs进行命名,从EventArgs类派生然后添加事件的成员,
  10. 如果不需要事件提供数据的类,可以使用系统的System.EventArgs类作为类型
  11. Eg: Public delegate void EventNameEventHander(Object sender,EventNameEventArgs e)  //声明委托
  12. 通常我们需要在引发事件的类中提供一个受保护的方法以OnEventName进行命名。在该方法中引发事件
  13. Protected virtual void OnEventName(EventArgs e)
  14. {
  15.     if(EventName!=null)
  16.     {
  17.        EventName(this,e);
  18.     }
  19. }
  20. 响应事件时:
  21.     实例。EventName+= new EventNameEventHander(响应事件的方法)
  22.     public void 响应事件的方法 (参数要与托管一致){
  23.     
  24. }
  25.  * 如果你想要更改该模板,那么请使用“工具 | 选项 | 编辑 | 编辑标准标题”。
  26.  */
  27. using System;
  28. using System.Collections.Generic;
  29. namespace Devent
  30.  public delegate void RunEventHandler(object sender ,RunEventArgs e);
  31.  class RunEventArgs:System.EventArgs
  32.  {private readonly int  P_Distance;
  33.   public RunEventArgs(int i){
  34.    this.P_Distance =i;
  35.   }
  36.   public int Distance{
  37.    get{return this.P_Distance;}
  38.   }
  39.  }
  40.  class person
  41.  {
  42.   public  event RunEventHandler Run;
  43.   protected virtual void onRun (object sender,RunEventArgs e)
  44.   {
  45.    RunEventHandler Handler = Run;
  46.    if (Handler != null)
  47.    {
  48.     Run(this , e);
  49.    }
  50.   }
  51.   public void go ()
  52.   {
  53.    int i ;
  54.    for (i=0 ;i<=100000 ;i++)
  55.    {
  56.     if (i%1000==0 )
  57.     {
  58.      onRun(thisnew RunEventArgs(i));
  59.     }
  60.    }
  61.   }
  62.  }
  63.  class MainClass
  64.  {
  65.   public static void Main(string[] args)
  66.   {
  67.    Console.WriteLine("Hello World!");
  68.    person p = new person();
  69.    p.Run += new RunEventHandler(run);
  70.    Console.Read();
  71.    p.go ();
  72.    Console.Read();
  73.   
  74.   }
  75.    static void  run(object sender,RunEventArgs e)
  76.   {
  77.    Console.WriteLine("Run" +e.Distance );
  78.   }
  79.  }
  80. }
原创粉丝点击