- /*
- * 由 SharpDevelop 创建。
- * 用户: zhaojp
- * 日期: 2008-12-2
- * 时间: 11:12
- * 照.NET FrameWork的事件设计准则去书写代码
- 1 事件的命名应遵循PascalCasing命名方式
- 2 申明delegate时使用void作为返回类型,事件接受两个传入参数一律命名为sender和e
- 3 定义一个事件提供数据的类对类以EventNameEventArgs进行命名,从EventArgs类派生然后添加事件的成员,
- 如果不需要事件提供数据的类,可以使用系统的System.EventArgs类作为类型
- Eg: Public delegate void EventNameEventHander(Object sender,EventNameEventArgs e) //声明委托
- 通常我们需要在引发事件的类中提供一个受保护的方法以OnEventName进行命名。在该方法中引发事件
- Protected virtual void OnEventName(EventArgs e)
- {
- if(EventName!=null)
- {
- EventName(this,e);
- }
- }
- 响应事件时:
- 实例。EventName+= new EventNameEventHander(响应事件的方法)
- public void 响应事件的方法 (参数要与托管一致){
- }
- * 如果你想要更改该模板,那么请使用“工具 | 选项 | 编辑 | 编辑标准标题”。
- */
- using System;
- using System.Collections.Generic;
- namespace Devent
- {
- public delegate void RunEventHandler(object sender ,RunEventArgs e);
- class RunEventArgs:System.EventArgs
- {private readonly int P_Distance;
- public RunEventArgs(int i){
- this.P_Distance =i;
- }
- public int Distance{
- get{return this.P_Distance;}
- }
- }
- class person
- {
- public event RunEventHandler Run;
- protected virtual void onRun (object sender,RunEventArgs e)
- {
- RunEventHandler Handler = Run;
- if (Handler != null)
- {
- Run(this , e);
- }
- }
- public void go ()
- {
- int i ;
- for (i=0 ;i<=100000 ;i++)
- {
- if (i%1000==0 )
- {
- onRun(this, new RunEventArgs(i));
- }
- }
- }
- }
- class MainClass
- {
- public static void Main(string[] args)
- {
- Console.WriteLine("Hello World!");
- person p = new person();
- p.Run += new RunEventHandler(run);
- Console.Read();
- p.go ();
- Console.Read();
- }
- static void run(object sender,RunEventArgs e)
- {
- Console.WriteLine("Run" +e.Distance );
- }
- }
- }
C# 事件机制实例
最新推荐文章于 2022-10-27 14:56:15 发布