48. C# -- 事件

來源:互聯網
上載者:User

標籤:c#

C# 事件(Event)


理論:

事件(Event) 基本上說是一個使用者操作,如按鍵、點擊、滑鼠移動等等,或者是一些出現,如系統產生的通知。

應用程式需要在事件發生時響應事件。例如,中斷。

事件是用於處理序間通訊。

通過事件使用委託 事件在類中聲明且產生,且通過使用同一個類或其他類中的委託與事件處理常式關聯。

包含事件的類用於發布事件。這被稱為 發布器(publisher) 類。

其他接受該事件的類被稱為 訂閱器(subscriber) 類。


通過事件使用委託

事件在類中聲明且產生,且通過使用同一個類或其他類中的委託與事件處理常式關聯。包含事件的類用於發布事件。這被稱為 發布器(publisher) 類。其他接受該事件的類被稱為 訂閱器(subscriber) 類。事件使用 發布-訂閱(publisher-subscriber) 模型。

發布器(publisher) 是一個包含事件和委託定義的對象。事件和委託之間的聯絡也定義在這個對象中。發布器(publisher)類的對象調用這個事件,並通知其他的對象。

訂閱器(subscriber) 是一個接受事件並提供事件處理常式的對象。在發布器(publisher)類中的委託調用訂閱器(subscriber)類中的方法(事件處理常式)。

聲明事件(Event)

在類的內部聲明事件,首先必須聲明該事件的委託類型。例如:

public delegate void BoilerLogHandler(string status);


然後,聲明事件本身,使用 event 關鍵字:


// 基於上面的委託定義事件

public event BoilerLogHandler BoilerEventLog;

上面的代碼定義了一個名為 BoilerLogHandler 的委託和一個名為 BoilerEventLog 的事件,該事件在產生的時候會調用委託。

執行個體 1
using System;namespace SimpleEvent{    using System;    public class EventTest{        //初始化value=0;        private int value;        public delegate void NumManipulationHandler();        //初始化ChangeNum=null;        public event NumManipulationHandler ChangeNum;        protected virtual void OnNumChanged(){            if (ChangeNum != null){            ChangeNum();}            else{                Console.WriteLine("Event fired!");}}        //初始化建構函式        public EventTest(int n){            SetValue(n);}        public void SetValue(int n){            if (value != n){            value = n;            OnNumChanged();}}}    public class MainClass{        public static void Main(){            EventTest e = new EventTest(5);            e.SetValue(7);            e.SetValue(11);            Console.ReadKey();}}}

當上面的代碼被編譯和執行時,它會產生下列結果:

Event Fired!

Event Fired!

Event Fired!



執行個體 2

本執行個體提供一個簡單的用於熱水鍋爐系統故障排除的應用程式。當維修工程師檢查鍋爐時,鍋爐的溫度和壓力會隨著維修工程師的備忘自動記錄到記錄檔中。

using System;using System.IO;namespace BoilerEventAppl{   // boiler 類   class Boiler   {      private int temp;      private int pressure;      public Boiler(int t, int p)      {         temp = t;         pressure = p;      }      public int getTemp()      {         return temp;      }      public int getPressure()      {         return pressure;      }   }   // 事件發布器   class DelegateBoilerEvent   {      public delegate void BoilerLogHandler(string status);      // 基於上面的委託定義事件      public event BoilerLogHandler BoilerEventLog;      public void LogProcess()      {         string remarks = "O. K";         Boiler b = new Boiler(100, 12);         int t = b.getTemp();         int p = b.getPressure();         if(t > 150 || t < 80 || p < 12 || p > 15)         {            remarks = "Need Maintenance";         }         OnBoilerEventLog("Logging Info:\n");         OnBoilerEventLog("Temparature " + t + "\nPressure: " + p);         OnBoilerEventLog("\nMessage: " + remarks);      }      protected void OnBoilerEventLog(string message)      {         if (BoilerEventLog != null)         {            BoilerEventLog(message);         }      }   }   // 該類保留寫入記錄檔的條款   class BoilerInfoLogger   {      FileStream fs;      StreamWriter sw;      public BoilerInfoLogger(string filename)      {         fs = new FileStream(filename, FileMode.Append, FileAccess.Write);         sw = new StreamWriter(fs);      }      public void Logger(string info)      {         sw.WriteLine(info);      }      public void Close()      {         sw.Close();         fs.Close();      }   }   // 事件訂閱器   public class RecordBoilerInfo   {      static void Logger(string info)      {         Console.WriteLine(info);      }//end of Logger      static void Main(string[] args)      {         BoilerInfoLogger filelog = new BoilerInfoLogger("e:\\boiler.txt");         DelegateBoilerEvent boilerEvent = new DelegateBoilerEvent();         boilerEvent.BoilerEventLog += new          DelegateBoilerEvent.BoilerLogHandler(Logger);         boilerEvent.BoilerEventLog += new          DelegateBoilerEvent.BoilerLogHandler(filelog.Logger);         boilerEvent.LogProcess();         Console.ReadLine();         filelog.Close();      }//end of main   }//end of RecordBoilerInfo}


當上面的代碼被編譯和執行時,它會產生下列結果:

Logging info:T

emperature 100

Pressure 12

Message: O. K


參考:


http://outofmemory.cn/csharp/tutorial/csharp-event.html 

本文出自 “Ricky's Blog” 部落格,請務必保留此出處http://57388.blog.51cto.com/47388/1656271

48. C# -- 事件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.