C\

From , 4 Years ago, written in C#, viewed 52 times.
URL https://pastebin.vip/view/50adecfc
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Delegate {
  5.     // 热水器
  6.     public class Heater {
  7.        private int temperature;
  8.        public delegate void BoilHandler(int param);   //声明委托
  9.        public event BoilHandler BoilEvent;        //声明事件
  10.        // 烧水
  11.        public void BoilWater() {
  12.            for (int i = 0; i <= 100; i++) {
  13.               temperature = i;
  14.               if (temperature > 95) {
  15.                   if (BoilEvent != null) { //如果有对象注册
  16.                       BoilEvent(temperature);  //调用所有注册对象的方法
  17.                   }
  18.               }
  19.            }
  20.        }
  21.     }
  22.     // 警报器
  23.     public class Alarm {
  24.        public void MakeAlert(int param) {
  25.            Console.WriteLine("Alarm:嘀嘀嘀,水已经 {0} 度了:", param);
  26.        }
  27.     }
  28.     // 显示器
  29.     public class Display {
  30.        public static void ShowMsg(int param) { //静态方法
  31.            Console.WriteLine("Display:水快烧开了,当前温度:{0}度。", param);
  32.        }
  33.     }
  34.      
  35.     class Program {
  36.        static void Main() {
  37.            Heater heater = new Heater();
  38.            Alarm alarm = new Alarm();
  39.            heater.BoilEvent += alarm.MakeAlert;    //注册方法
  40.            heater.BoilEvent += (new Alarm()).MakeAlert;   //给匿名对象注册方法
  41.            heater.BoilEvent += Display.ShowMsg;       //注册静态方法
  42.            heater.BoilWater();   //烧水,会自动调用注册过对象的方法
  43.        }
  44.     }
  45. }
  46.  
  47. //csharp/6897

Reply to "C\"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website