• c#事件实例三


    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();
    
                //这个大概就是 我们事件滴使用了滴把;
                //把我们的观察着,设计 模式 看懂了,那么 就算是明白了一点点了滴呀;
    
    
            }
        }
    }

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

  • 相关阅读:
    react fake double , bind click and dblclick on the same element
    Microbit MicroPython 介绍
    树莓派Raspberry Pi微改款,Model B 3+规格探析
    用Micro:bit做剪刀、石头、布游戏
    用Micro:bit做交通信号灯
    树莓派 Raspberry Pi 与 micro:bit起手式
    Microbit蓝芽配对
    micro:bit 软件生态系统介绍
    Micro:bit 硬件架构介绍
    Ruby 学习笔记7
  • 原文地址:https://www.cnblogs.com/mc67/p/5076163.html
Copyright © 2020-2023  润新知