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

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

  • 相关阅读:
    Unity3D鼠标点击处
    Unity3D静态AI自动寻路
    Unity3D 雷达检测器
    Unity3D重新加载光线变暗问题
    Unity3D切换场景不销毁物体
    软件&环境&网页
    2020软件工程作业05
    2020软件工程作业04
    利用Java输入输出流更改文件中指定的内容
    2020软件工程作业03
  • 原文地址:https://www.cnblogs.com/mc67/p/5076163.html
Copyright © 2011-2022 走看看