委托
1. C# 中的委托類似于 C 或 C++ 中指向函式的指標,委托表示參考某個方法的參考型別變數,運行時可以更改參考物件,
2. 特別地,委托可以用于處理事件或回呼函式,并且,所有的委托類都是從 System.Delegate 類繼承而來,
宣告委托的語法規則:(被委托所參考的方法需有相同的引數和回傳值)
delegate <return type> <delegate-name> <parameter list>
一個委托使用示例:
using System; public delegate void Mydelegate(string str); //創建委托實體 namespace Delegate { class TextMethods { public static void Method1(string str) { Console.WriteLine("這是方法1,{0}",str); } public static void Method2(string str) { Console.WriteLine("這是方法2,{0}",str); } public static void Method3(string str) { Console.WriteLine("這是方法3,{0}", str); } } class Program { static void Main(string[] args) { Mydelegate d1, d2, d3; //定義委托變數 d1 = TextMethods.Method1; d2 = TextMethods.Method2; d3 = TextMethods.Method3; d1("1"); //呼叫委托實體 d2("2"); d3("3"); Console.WriteLine(""); Mydelegate d4; d4 = TextMethods.Method1; d4 += TextMethods.Method2; //添加實體 d4 += TextMethods.Method3; d4("4"); Console.WriteLine(""); d4 -= TextMethods.Method3; //移除實體 d4("5"); Console.WriteLine(""); } } }
事件
事件是應用程式在執行程序中所關注的一些動作,但這些動作發生時,程式需要對其做出回應,事件的概念比較廣泛,所有程式需要進行回應處理的動作都可以稱為事件,如滑鼠單擊、鍵盤輸入、計時器訊息...
事件基于委托,為委托提供了一種發布/訂閱機制,在.NET架構內外都可以看到事件,在Windows應用程式中,Button類提供了Click事件,這類事件就是委托,觸發Click事件呼叫的處理程式需要得到定義,而其引數由委托型別定義,
事件機制是以訊息為基礎的,當特定的動作發生后會產生相應的訊息,關注該事件的應用程式收到事件發生的訊息,就會開始指定處理程序,
示例:
參考自:[w3cSchool] https://www.w3cschool.cn/wkcsharp/yvoj1nvx.html"%3Ehttps://www.w3cschool.cn/wkcsharp/yvoj1nvx.html%3C/a%3E
該示例為一個簡單的應用程式,該程式用于熱水鍋爐系統故障排除,當維修工程師檢查鍋爐時,鍋爐的溫度、壓力以及工程師所寫的備注都會被自動記錄到一個日志檔案中,
示例中可以看出,在主函式中,創建了事件發布器類(DelegateBoilerEvent),并將一個寫入檔案的(訂閱器)和一個控制臺輸出函式添加進事件示例中,在執行觸發器類中的記錄程序函式(LogProcess() )時,就會呼叫所有添加進事件的函式實體,
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) //函式在發布器類中,當要進行發布時,就觸發事件BoilerEventLog所添加的實體 { 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("?boiler.txt"); //打開日志檔案 DelegateBoilerEvent boilerEvent = new DelegateBoilerEvent(); //實體化DelegateBoilerEvent類,事件發布器 boilerEvent.BoilerEventLog += new DelegateBoilerEvent.BoilerLogHandler(Logger); //boilerEvent.BoilerEventLog為委托的實體,將Logger添加進委托 boilerEvent.BoilerEventLog += new DelegateBoilerEvent.BoilerLogHandler(filelog.Logger); //filelog是BoilerInfoLogger類的實體化,將其中的Logger函式添加進委托 boilerEvent.LogProcess(); //執行LogProccess函式 filelog.Close(); }//end of main }//end of RecordBoilerInfo }
執行結果:
Logging Info: Temparature 100 Pressure: 12 Message: O. K
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/120873.html
標籤:C#
下一篇:型別和變數(C#學習筆記02)
