• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Dreama
只想要简简单单的快乐!
博客园    首页    新随笔    联系   管理     
C# 事件与委托
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ConsoleApplication
 8 {
 9     class Program
10     {
11         static void Main(string[] args) //客户端
12         {
13             Heater t = new Heater(); //初始化Heater类的实例
14             t.Boiled += new BoiledEventHandler(new Monitor().Display);//在监视对象(热水器)中为观察者(显示器)实例方法事件的注册
15             t.BoilingWater();//Heater类实例对Boiled事件的触发,以便更新观察者(显示器)中的数据
16             Console.ReadKey();
17         }
18     }
19 
20     class BoiledEventArgs : EventArgs //事件类,存储观察者对监视对象(热水器)所感兴趣的字段(如Temperature)
21     {
22         public readonly int Tempurature;
23         public BoiledEventArgs(int tempurature)
24         {
25             Tempurature = tempurature;
26         }
27     }
28     delegate void BoiledEventHandler(object sender,BoiledEventArgs e); //定义一个委托
29     class Heater //监视对象(热水器)
30     {
31         int _Temperature;//令观察者(显示器)感兴趣的字段:温度
32         public string Brand = "Midea";
33         public event BoiledEventHandler Boiled;//事件委托:观察者(显示器)对监视对象(热水器)所调用的方法
34         protected virtual void OnBoiled(BoiledEventArgs e)
35         {
36             if (Boiled != null)
37             {
38                 Boiled(this, e);//事件绑定:如客户端(一般指Main函数)已有观察者(显示器)对监视对象(热水器)的事件(Boiled)进行订阅,
39                                 //则进行对观察者(显示器)数据(Temperature:温度)的更新显示
40             }
41         }
42 
43         public void BoilingWater()
44         {
45             for (int i = 0; i <= 100; i++)
46             {
47                 _Temperature= i;
48                 if (i > 90)
49                 {
50                     BoiledEventArgs e = new BoiledEventArgs(_Temperature);//事件类的构造函数,传递观察者(显示器)所感兴趣的字段(温度)
51                     OnBoiled(e);//对Boiled事件进行触发,以便使观察者(显示器)数据(Temperature:温度)得到更新
52                 }
53             }
54         }
55     }
56 
57     class Monitor //观察者(显示器)
58     {
59         public void Display(object sender, BoiledEventArgs e)
60         {
61             Heater t = (Heater)sender;//sender,来自Heater类,可以对实例的字段等进行访问,
62             Console.WriteLine("Brand is " + t.Brand);//如访问该热水器的品牌
63             Console.WriteLine("Current temperature is " + e.Tempurature);//观察者(显示器)本身数据的更新显示
64         }
65     }
66 }

参考来自:http://www.cnblogs.com/jimmyzhang/archive/2007/09/23/903360.html

posted on 2014-03-11 10:09  Dreamma  阅读(355)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3

© 本文章版权归 Dreama 所有, 转载授权请联系: cnxy@88.com

如果本文对您有帮助,欢迎支持原创

支付宝

支付宝扫码支持

微信

微信赞赏支持