zoukankan      html  css  js  c++  java
  • C# 中的委托和事件

    参考:https://www.cnblogs.com/lonelyxmas/archive/2009/10/28/1591118.html

    Observer设计模式

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace Delegate {
        // 热水器
        public class Heater {
           private int temperature;
           public delegate void BoilHandler(int param);   //声明委托
           public event BoilHandler BoilEvent;        //声明事件
    
           // 烧水
           public void BoilWater() {
               for (int i = 0; i <= 100; i++) {
                  temperature = i;
    
                  if (temperature > 95) {
                      if (BoilEvent != null) { //如果有对象注册
                          BoilEvent(temperature);  //调用所有注册对象的方法
                      }
                  }
               }
           }
        }
    
        // 警报器
        public class Alarm {
           public void MakeAlert(int param) {
               Console.WriteLine("Alarm:嘀嘀嘀,水已经 {0} 度了:", param);
           }
        }
    
        // 显示器
        public class Display {
           public static void ShowMsg(int param) { //静态方法
               Console.WriteLine("Display:水快烧开了,当前温度:{0}度。", param);
           }
        }
        
        class Program {
           static void Main() {
               Heater heater = new Heater();
               Alarm alarm = new Alarm();
    
               heater.BoilEvent += alarm.MakeAlert;    //注册方法
               heater.BoilEvent += (new Alarm()).MakeAlert;   //给匿名对象注册方法
               heater.BoilEvent += Display.ShowMsg;       //注册静态方法
    
               heater.BoilWater();   //烧水,会自动调用注册过对象的方法
           }
        }
    }

    输出为:
    Alarm:嘀嘀嘀,水已经 96 度了:
    Alarm:嘀嘀嘀,水已经 96 度了:
    Display:水快烧开了,当前温度:96度。
    // 省略...

    补充:

    代码中的

      if (BoilEvent != null) { //如果有对象注册
                          BoilEvent(temperature);  //调用所有注册对象的方法
                      }

    在VS2017中被提示改为了?语法。

    BoilEvent?.Invoke(temperature);  //调用所有注册对象的方法

  • 相关阅读:
    伪多项式时间 Pseudo-polynomial time
    Aho-Corasick算法
    写给十八岁以下的你
    网络流算法
    Java static关键字
    带有负权边的最短路径问题
    Miller_Rabin(米勒拉宾)素数测试
    关于同余与模运算的总结
    UVa1585
    UVa修改版02
  • 原文地址:https://www.cnblogs.com/pu369/p/9988317.html
Copyright © 2011-2022 走看看