当前位置:   article > 正文

C#event EventHandler事件触发

C#event EventHandler事件触发

 

在定义委托时,前面加上event关键字,可以保证该委托不能在外部被随意触发,两者异同:

 注册注销内部触发外部触发
delegate+=-=InvokeInvoke
event delegate+=-=Invoke不允许

所以,event关键字有助于提高类的封装性,物理隔绝代码耦合,迫使类设计更追求高内聚。

定义一个显示消息的event并包装

  1. public event EventHandler evt_log_handle;
  2. protected virtual void On_evt_log_handle(object obj, EventArgs e)
  3. {
  4. if (this.evt_log_handle != null)
  5. this.evt_log_handle(obj, e);
  6. }

在外部触发:

On_evt_log_handle("日志", null);

在其他类中,可以注册这个事件

m_project.evt_log_handle += m_process_evt_log_handle;  m_project为定义event的类的实例

定义事件实现的代码

  1. void m_process_evt_log_handle(object sender, EventArgs e)
  2. {
  3. string sLog = sender as string;
  4. ...
  5. }

 控制台输入'a'累加到上限实现事件的示例

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace ConsoleApp2
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. Counter c = new Counter(new Random().Next(10));
  13. c.ThresholdReached += c_ThresholdReached; //注册事件
  14. Console.WriteLine("press 'a' key to increase total");
  15. while (Console.ReadKey(true).KeyChar == 'a')
  16. {
  17. Console.WriteLine("adding one");
  18. c.Add(1);
  19. }
  20. }
  21. static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e) //事件实现
  22. {
  23. Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
  24. Environment.Exit(0);
  25. }
  26. }
  27. class Counter
  28. {
  29. private int threshold;
  30. private int total;
  31. public Counter(int passedThreshold)
  32. {
  33. threshold = passedThreshold;
  34. }
  35. public void Add(int x)
  36. {
  37. total += x;
  38. if (total >= threshold)
  39. {
  40. ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
  41. args.Threshold = threshold;
  42. args.TimeReached = DateTime.Now;
  43. OnThresholdReached(args);
  44. }
  45. }
  46. public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;
  47. protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
  48. {
  49. if (this.ThresholdReached != null)
  50. {
  51. this.ThresholdReached(null, e);
  52. }
  53. }
  54. }
  55. public class ThresholdReachedEventArgs : EventArgs
  56. {
  57. public int Threshold { get; set; }
  58. public DateTime TimeReached { get; set; }
  59. }
  60. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/984206
推荐阅读
相关标签
  

闽ICP备14008679号