C#自定义事件监听实现方法

2019-12-26 13:05:41王冬梅

易采站长站为您分析C#自定义事件监听实现方法,涉及C#事件监听的实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了C#自定义事件监听实现方法。。具体实现方法如下:

 

 
  1. using System;  using System.Collections.Generic; 
  2. using System.Linq;  using System.Text; 
  3. namespace ConsoleApp  { 
  4. /// <summary>  /// 定义事件 
  5. /// </summary>  class CustomEvent 
  6. {  /// <summary> 
  7. /// 定义委托  /// </summary> 
  8. /// <param name="sender"></param>  /// <param name="e"></param> 
  9. public delegate void UserRequest(object sender, EventArgs e);  /// <summary> 
  10. /// 此委托类型的事件  /// </summary> 
  11. public event UserRequest OnUserRequest;  public CustomEvent() 
  12. {  UserEventMonitor uem = new UserEventMonitor(this); 
  13. }  public void DoRun() 
  14. {  bool flag = false; 
  15. do  { 
  16. Console.WriteLine();  Console.WriteLine("请输入:"); 
  17. string result = Console.ReadLine();  if (result == "1") 
  18. {  if (OnUserRequest != null) 
  19. OnUserRequest(this, new EventArgs());  } 
  20. } while (!flag);  } 
  21. }  /// <summary> 
  22. /// 事件监听  /// </summary> 
  23. class UserEventMonitor  { 
  24. public UserEventMonitor(CustomEvent cem)  { 
  25. // cem.OnUserRequest += ShowMessage;  cem.OnUserRequest += delegate 
  26. {  Console.WriteLine("hello word!!"); 
  27. };  } 
  28. public void ShowMessage(object sender, EventArgs e)  { 
  29. Console.WriteLine("hello word!!");  }