日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

C# 事件和委托

發布時間:2025/7/14 C# 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C# 事件和委托 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 public class Heater { 2 private int temperature; 3 public string type = "RealFire 001"; // 添加型號作為演示 4 public string area = "China Xian"; // 添加產地作為演示 5 //聲明委托 6 public delegate void BoiledEventHandler(Object sender, BoiledEventArgs e); 7 public event BoiledEventHandler Boiled; //聲明事件 8 9 // 定義BoiledEventArgs類,傳遞給Observer所感興趣的信息 10 public class BoiledEventArgs : EventArgs { 11 public readonly int temperature; 12 public BoiledEventArgs(int temperature) { 13 this.temperature = temperature; 14 } 15 } 16 17 // 可以供繼承自 Heater 的類重寫,以便繼承類拒絕其他對象對它的監視 18 protected virtual void OnBoiled(BoiledEventArgs e) { 19 if (Boiled != null) { // 如果有對象注冊 20 Boiled(this, e); // 調用所有注冊對象的方法 21 } 22 } 23 24 // 燒水。 25 public void BoilWater() { 26 for (int i = 0; i <= 100; i++) { 27 temperature = i; 28 if (temperature > 95) { 29 //建立BoiledEventArgs 對象。 30 BoiledEventArgs e = new BoiledEventArgs(temperature); 31 OnBoiled(e); // 調用 OnBolied方法 32 } 33 } 34 } 35 } 36 37 // 警報器 38 public class Alarm { 39 public void MakeAlert(Object sender, Heater.BoiledEventArgs e) { 40 Heater heater = (Heater)sender; //這里是不是很熟悉呢? 41 //訪問 sender 中的公共字段 42 Console.WriteLine("Alarm:{0} - {1}: ", heater.area, heater.type); 43 Console.WriteLine("Alarm: 嘀嘀嘀,水已經 {0} 度了:", e.temperature); 44 Console.WriteLine(); 45 } 46 } 47 48 // 顯示器 49 public class Display { 50 public static void ShowMsg(Object sender, Heater.BoiledEventArgs e) { //靜態方法 51 Heater heater = (Heater)sender; 52 Console.WriteLine("Display:{0} - {1}: ", heater.area, heater.type); 53 Console.WriteLine("Display:水快燒開了,當前溫度:{0}度。", e.temperature); 54 Console.WriteLine(); 55 } 56 }

定義委托,事件是委托的對象,事件對類外暴露,以供其他類調用。

protect修飾符,僅限類和派生類訪問。

轉載于:https://www.cnblogs.com/slarkleoric/p/6833012.html

總結

以上是生活随笔為你收集整理的C# 事件和委托的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。