How to: Raise and Consume Events

王朝学院·作者佚名  2016-05-17
窄屏简体版  字體: 小  |  中  |  大  |  超大  

How to: Raise and Consume Eventsusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Consoleapplication1{ class PRogram { static void Main(string[] args) { Counter counter = new Counter(new Random().Next(10)); // 4. subscribe event counter.ThresholdReached += counter_ThresholdReached; Console.WriteLine("press 'a' key to increase total"); while (Console.ReadKey(true).KeyChar == 'a') { Console.WriteLine("adding one"); counter.Add(1); } } static void counter_ThresholdReached(object sender, ThresholdEventArgs e) { Console.WriteLine("Threshold " + e.ThresholdNum + " reached at time "+ e.TimeReached); } } public class Counter { int threshold; int total; public Counter(int thresholdVal) { threshold = thresholdVal; } public void Add(int x) { total += x; // 5. trigger event if (total > threshold) { ThresholdEventArgs args = new ThresholdEventArgs(); args.ThresholdNum = threshold; args.TimeReached = DateTime.Now; OnThresholdReached(this, args); } } // 1. define event public event EventHandler<ThresholdEventArgs> ThresholdReached; // 2. define OnXXX virtual method public virtual void OnThresholdReached(object sender, ThresholdEventArgs e) { EventHandler<ThresholdEventArgs> handler = ThresholdReached; if (handler != null) handler(this, e); } } // 3. define event arguments public class ThresholdEventArgs : EventArgs { public int ThresholdNum { get; set; } public DateTime TimeReached { get; set; } }}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航