事件简单例子

 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 }

 

转载于:https://www.cnblogs.com/niaomingjian/p/3764413.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值