码迷,mamicode.com
首页 > 其他好文 > 详细

事件简单例子

时间:2014-06-02 18:26:00      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

bubuko.com,布布扣
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Runtime.InteropServices;
 6 
 7 namespace EventTest
 8 {
 9     /// <summary>
10     /// 事件订阅者类
11     /// </summary>
12     class Program
13     {
14         static void Main(string[] args)
15         {
16             Counter c = new Counter(new Random().Next(10));
17             c.ThresholdReached += c_ThresholdReached;  // 订阅事件(注册事件)
18 
19             Console.WriteLine("press ‘a‘ key to increase total");
20             while(Console.ReadKey(true).KeyChar==a)
21             {
22                 Console.WriteLine("adding one");
23                 c.Add(1);
24             }
25             Console.ReadLine();
26         }
27 
28         static void c_ThresholdReached(object sender, CounterEventArgs e) // 事件处理程序
29         {
30             Console.WriteLine("The threshold was reached And Value is {0}.",e.total);
31             //Environment.Exit(0);
32         }
33     }
34 
35     /// <summary>
36     /// 事件数据类
37     /// </summary>
38     public class CounterEventArgs : EventArgs
39     {
40         public int total;
41         public CounterEventArgs(int passedTotal)
42         {
43             total = passedTotal;
44         }
45     }
46 
47     /// <summary>
48     /// 事件发布者类 
49     /// </summary>
50     /// <remarks>
51     /// 功能:实现total值的不断增加。达到阈值时触发事件给出达到阈值的提示。
52     /// </remarks>
53     public class Counter
54     {
55         public event EventHandler<CounterEventArgs> ThresholdReached;  // 声明事件
56 
57         private int total;
58         private int threshold;
59         public Counter(int passedThreshold)
60         {
61             threshold = passedThreshold;
62         }
63 
64         public void Add(int x)
65         {
66             total += x;
67             if (total >= threshold) // 在每次增加值之后判断是否触发事件
68             {
69                 CounterEventArgs cEArgs = new CounterEventArgs(total);
70                 OnThresholdReached(cEArgs); // 传递事件数据给事件处理程序
71             }
72         }
73 
74         protected virtual void OnThresholdReached(CounterEventArgs e) // 触发事件
75         {
76             EventHandler<CounterEventArgs> handler = ThresholdReached;
77             if (handler != null)
78             {
79                 handler(this, e);
80             }
81         }
82     }
83 }
bubuko.com,布布扣

 bubuko.com,布布扣

事件简单例子,布布扣,bubuko.com

事件简单例子

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/niaomingjian/p/3764413.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!