首页 > 其他 > 详细

C# 事件与委托

时间:2014-03-11 21:57:38      阅读:434      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 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 }
bubuko.com,布布扣

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

C# 事件与委托,布布扣,bubuko.com

C# 事件与委托

原文:http://www.cnblogs.com/cncc/p/3593292.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!