前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C# 事件与委托

C# 事件与委托

作者头像
CNXY
发布2017-12-25 15:28:21
6980
发布2017-12-25 15:28:21
举报
文章被收录于专栏:C# 编程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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-03-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档