C#委托和事件 EventHandle和EventArgs

一、背景
由于对于C#委托和事件理解的不够透彻,并且平时工作中对于自己手写委托和事件很少,渐渐的只会增删改查了。特定整理了委托和事件的基本知识。
二、案例
案例引用了 张逸 博客 中的案例,并做了处理。

  创建一个控制台项目,监测根目录下是否有text.txt文件。

  创建一个简单的类,名为FileWatch,包含事件FileWatchevent。该类将检查在执行应用程序的目录(当前

  目录,通常是项目名/bin/debug)下,是否存在文件text.txt。如果文件被删除或创建,都将触发事件。

  同时提供一个方法MonitorFile以不断地查询该文件。

  代码中有注释,看着方便

  

 1   //定义委托
 2     public delegate void FileWatchEventHandler(object sender, EventArgs e);
 3     /// <summary>
 4     /// 定义FileWatch 类
 5     /// </summary>
 6     public class FileWatch
 7     {
 8         //定义事件
 9         public event FileWatchEventHandler FileWatchevent;
10 
11         /// <summary>
12         /// 用于检测test.txt 文件状态
13         /// </summary>
14         public void MonitorFile()
15         {
16             bool isExist = false;
17             while (true)
18             {
19                 isExist = File.Exists("test.txt");
20                 MyEventAgrs arg = new MyEventAgrs();
21                 arg.State = isExist ? "存在" : "不存在";
22 
23                 if (FileWatchevent != null)
24                 {
25                     FileWatchevent(this, arg);
26                 }
27 
28                 Thread.Sleep(200);
29             }
30         }
31 
32     }
33     /// <summary>
34     /// MyEventAgrs ,用户返回文件状态
35     /// </summary>
36     public class MyEventAgrs : EventArgs
37     {
38         private string _state;
39 
40         public string State
41         {
42             get { return this._state; }
43             set { _state = value; }
44         }
45     }

下面是调用方法:

 

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {  //实例化
 5        FileWatch fw = new FileWatch();
 6 
 7             //注册事件
 8             fw.FileWatchevent += new FileWatchEventHandler(OnFileChange);
 9 
10             //另开一个线程,用于检测文件
11             Thread t = new Thread(fw.MonitorFile);
12             t.Start();
13 
14             Thread.Sleep(1000);
15             var filePath = AppDomain.CurrentDomain.BaseDirectory;
16             filePath = filePath + "test.txt";
17             var fileStream = File.Create(filePath);
18             fileStream.Close();//注意关闭流,否则下面的删除会报错
19 
20 
21             Thread.Sleep(1000);
22             File.Delete(filePath);
23 
24             Console.ReadKey();
25         }
26 
27         private static void OnFileChange(object sender, EventArgs e)
28         {
29             MyEventAgrs arg = e as MyEventAgrs;//用于获取文件的状态
30             Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + arg.State);
31         }
32     }

运行结果:

 

三总结:

1、创建委托:
public delegate void 委托名(object sender, EventArgs e);

2、如果有获取状态,需要创建类,继承EventArgs 

3、创建事件:

public event 委托类型 事件名;

4、注册事件,并添加其处理方法

 

部分引用来自:http://wayfarer.cnblogs.com/archive/2004/04/20/6712.html

                                              

posted @ 2017-08-17 21:40  mengxuef  阅读(531)  评论(0编辑  收藏  举报
TOP