博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c#事件实例三
阅读量:4691 次
发布时间:2019-06-09

本文共 1739 字,大约阅读时间需要 5 分钟。

c#事件实例三

监视test.txt 文件的状态滴呀!

 直接上代码;

using System;using System.Threading;using System.IO;namespace EventLearn003{    public delegate void FileWatchHanlder(Object sender,EventArgs e);    //这个,相当于事件的发生了;   public class FileWatch    {       private bool _bLastStatus = false;       public event FileWatchHanlder FileWatching;       public FileWatch()       {           //这个大概就是我们的基本的代码滴啦;           //然后我们把他生成dll 然后 在别的项目中别引用滴呀;       }       protected virtual void OnFileChange(EventArgs e)       {           if (FileWatching != null)           {               //需要触发事件的地方 调用delegate的方式写触发方法,一般为protected 类型的 虚方法;               FileWatching(this,e);                //调用事件;           }       }       public void MonitorFile()       {           bool bCurrentStatus;           while (true)           {               bCurrentStatus = File.Exists("test.txt");               if (bCurrentStatus != _bLastStatus)               {                   _bLastStatus = bCurrentStatus;                   OnFileChange(EventArgs.Empty);               }               Thread.Sleep(260);           }       }    }}

事件接受类:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using EventLearn003;namespace EventLearn003{    class Program    {        public static void en(Object sender, EventArgs e)        {            Console.WriteLine("状态呗改变了...");        }        static void Main(string[] args)        {            //事件的接受类滴呀;            FileWatch help = new FileWatch();            help.FileWatching += en;            help.MonitorFile();            //这个大概就是 我们事件滴使用了滴把;            //把我们的观察着,设计 模式 看懂了,那么 就算是明白了一点点了滴呀;        }    }}

好了,我们事件讲解就算是到一段落了滴呀;

 

转载于:https://www.cnblogs.com/mc67/p/5076163.html

你可能感兴趣的文章