C# 事件

C# 事件(Event)

事件(Event) 基本上说是一个用户操作,如按键、点击、鼠标移动等等,或者是一些出现,如系统生成的通知。应用程序需要在事件发生时响应事件。例如,中断。事件是用于进程间通信。

通过事件使用委托

事件在类中声明且生成,且通过使用同一个类或其他类中的委托与事件处理程序关联。包含事件的类用于发布事件。这被称为发布器(publisher) 类。其他接受该事件的类被称为 订阅器(subscriber) 类。事件使用 发布-订阅(publisher-subscriber) 模型。

发布器(publisher) 是一个包含事件和委托定义的对象。事件和委托之间的联系也定义在这个对象中。发布器(publisher)类的对象调用这个事件,并通知其他的对象。

订阅器(subscriber) 是一个接受事件并提供事件处理程序的对象。在发布器(publisher)类中的委托调用订阅器(subscriber)类中的方法(事件处理程序)。

声明事件(Event)

在类的内部声明事件,首先必须声明该事件的委托类型。例如:

[csharp]  view plain  copy
  1. public delegate void BoilerLogHandler(string status);  

然后,声明事件本身,使用 event 关键字:

[csharp]  view plain  copy
  1. // 基于上面的委托定义事件  
  2. public event BoilerLogHandler BoilerEventLog;  

上面的代码定义了一个名为 BoilerLogHandler 的委托和一个名为 BoilerEventLog 的事件,该事件在生成的时候会调用委托。

发布器与订阅器(publisher and subscriber)

[csharp]  view plain  copy
  1. using System;  
  2. namespace SimpleEvent  
  3. {  
  4.   using System;  
  5.   /***********发布器类***********/  
  6.   public class EventTest  
  7.   {  
  8.     private int value;  
  9.   
  10.     public delegate void NumManipulationHandler();  
  11.   
  12.   
  13.     public event NumManipulationHandler ChangeNum;  
  14.     protected virtual void OnNumChanged()  
  15.     {  
  16.       if ( ChangeNum != null )  
  17.       {  
  18.         ChangeNum(); /* 事件被触发 */  
  19.       }else {  
  20.         Console.WriteLine( "event not fire" );  
  21.         Console.ReadKey(); /* 回车继续 */  
  22.       }  
  23.     }  
  24.   
  25.   
  26.     public EventTest()  
  27.     {  
  28.       int n = 5;  
  29.       SetValue( n );  
  30.     }  
  31.   
  32.   
  33.     public void SetValue( int n )  
  34.     {  
  35.       if ( value != n )  
  36.       {  
  37.         value = n;  
  38.         OnNumChanged();  
  39.       }  
  40.     }  
  41.   }  
  42.   
  43.   
  44.   /***********订阅器类***********/  
  45.   
  46.   public class subscribEvent  
  47.   {  
  48.     public void printf()  
  49.     {  
  50.       Console.WriteLine( "event fire" );  
  51.       Console.ReadKey(); /* 回车继续 */  
  52.     }  
  53.   }  
  54.   
  55.   /***********触发***********/  
  56.   public class MainClass  
  57.   {  
  58.     public static void Main()  
  59.     {  
  60.       EventTest e = new EventTest(); /* 实例化对象,第一次没有触发事件 */  
  61.       subscribEvent v = new subscribEvent(); /* 实例化对象 */  
  62.       e.ChangeNum += new EventTest.NumManipulationHandler( v.printf ); /* 注册 */  
  63.       e.SetValue( 7 );  
  64.       e.SetValue( 11 );  
  65.     }  
  66.   }  
  67. }  

当上面的代码被编译和执行时,它会产生下列结果:

[csharp]  view plain  copy
  1. event not fire  
  2. event fire  
  3. event fire  

经典案例-热水锅炉系统

本实例提供一个简单的用于热水锅炉系统故障排除的应用程序。当维修工程师检查锅炉时,锅炉的温度和压力会随着维修工程师的备注自动记录到日志文件中。

[csharp]  view plain  copy
  1. using System;  
  2. using System.IO;  
  3.   
  4. namespace BoilerEventAppl  
  5. {  
  6.   
  7.    // boiler 类  
  8.    class Boiler  
  9.    {  
  10.       private int temp;  
  11.       private int pressure;  
  12.       public Boiler(int t, int p)  
  13.       {  
  14.          temp = t;  
  15.          pressure = p;  
  16.       }  
  17.   
  18.       public int getTemp()  
  19.       {  
  20.          return temp;  
  21.       }  
  22.       public int getPressure()  
  23.       {  
  24.          return pressure;  
  25.       }  
  26.    }  
  27.    // 事件发布器  
  28.    class DelegateBoilerEvent  
  29.    {  
  30.       public delegate void BoilerLogHandler(string status);  
  31.   
  32.       // 基于上面的委托定义事件  
  33.       public event BoilerLogHandler BoilerEventLog;  
  34.   
  35.       public void LogProcess()  
  36.       {  
  37.          string remarks = "O. K";  
  38.          Boiler b = new Boiler(100, 12);  
  39.          int t = b.getTemp();  
  40.          int p = b.getPressure();  
  41.          if(t > 150 || t < 80 || p < 12 || p > 15)  
  42.          {  
  43.             remarks = "Need Maintenance";  
  44.          }  
  45.          OnBoilerEventLog("Logging Info:\n");  
  46.          OnBoilerEventLog("Temparature " + t + "\nPressure: " + p);  
  47.          OnBoilerEventLog("\nMessage: " + remarks);  
  48.       }  
  49.   
  50.       protected void OnBoilerEventLog(string message)  
  51.       {  
  52.          if (BoilerEventLog != null)  
  53.          {  
  54.             BoilerEventLog(message);  
  55.          }  
  56.       }  
  57.    }  
  58.    // 该类保留写入日志文件的条款  
  59.    class BoilerInfoLogger  
  60.    {  
  61.       FileStream fs;  
  62.       StreamWriter sw;  
  63.       public BoilerInfoLogger(string filename)  
  64.       {  
  65.          fs = new FileStream(filename, FileMode.Append, FileAccess.Write);  
  66.          sw = new StreamWriter(fs);  
  67.       }  
  68.       public void Logger(string info)  
  69.       {  
  70.          sw.WriteLine(info);  
  71.       }  
  72.       public void Close()  
  73.       {  
  74.          sw.Close();  
  75.          fs.Close();  
  76.       }  
  77.    }  
  78.    // 事件订阅器  
  79.    public class RecordBoilerInfo  
  80.    {  
  81.       static void Logger(string info)  
  82.       {  
  83.          Console.WriteLine(info);  
  84.       }//end of Logger  
  85.   
  86.       static void Main(string[] args)  
  87.       {  
  88.          BoilerInfoLogger filelog = new BoilerInfoLogger("e:\\boiler.txt");  
  89.          DelegateBoilerEvent boilerEvent = new DelegateBoilerEvent();  
  90.          boilerEvent.BoilerEventLog += new   
  91.          DelegateBoilerEvent.BoilerLogHandler(Logger);  
  92.          boilerEvent.BoilerEventLog += new   
  93.          DelegateBoilerEvent.BoilerLogHandler(filelog.Logger);  
  94.          boilerEvent.LogProcess();  
  95.          Console.ReadLine();  
  96.          filelog.Close();  
  97.       }//end of main  
  98.   
  99.    }//end of RecordBoilerInfo  
  100. }  

当上面的代码被编译和执行时,它会产生下列结果:

[csharp]  view plain  copy
  1. Logging info:  
  2.   
  3. Temperature 100  
  4. Pressure 12  
  5.   
  6. Message: O. K  

猜你喜欢

转载自blog.csdn.net/weixin_39029925/article/details/78212232