欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-01-10 16:47:03
本文实例讲述了c#自定义事件监听实现方法。分享给大家供大家参考。具体实现方法如下: using system; using system.collections...

本文实例讲述了c#自定义事件监听实现方法。分享给大家供大家参考。具体实现方法如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
namespace consoleapp
{
 /// <summary>
 /// 定义事件
 /// </summary>
 class customevent
 {
  /// <summary>
  /// 定义委托
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  public delegate void userrequest(object sender, eventargs e);
  /// <summary>
  /// 此委托类型的事件
  /// </summary>
  public event userrequest onuserrequest;
  public customevent()
  {
   usereventmonitor uem = new usereventmonitor(this);
  }
  public void dorun()
  {
   bool flag = false;
   do
   {
    console.writeline();
    console.writeline("请输入:");
    string result = console.readline();
    if (result == "1")
    {
     if (onuserrequest != null)
      onuserrequest(this, new eventargs());
    }
   } while (!flag);
  }
 }
 /// <summary>
 /// 事件监听
 /// </summary>
 class usereventmonitor
 {
  public usereventmonitor(customevent cem)
  {
   // cem.onuserrequest += showmessage;
   cem.onuserrequest += delegate
   {
    console.writeline("hello word!!");
   };
  }
  public void showmessage(object sender, eventargs e)
  {
   console.writeline("hello word!!");
  }
 }
 /// <summary>
 /// 调用类
 /// </summary>
 public class run
 {
  static void main(string[] args)
  {
   customevent cem = new customevent();
   cem.dorun();
   console.readline();
  }
 }
}

希望本文所述对大家的c#程序设计有所帮助。