本次只用一个实例,来说明在C#中如何使用自定义事件。
  写一个类,此类包含了自定义事件: onSendMsg。
  文件名:ChatServer.cs
  public class ChatServer
  {
   public delegate void MyEventHandler(string msg);
   public event MyEventHandler onSendMsg;
   public void SendMsg()
   {
   onSendMsg("开始发送消息!");
   }
  }
  文件名:Form1.cs
  ///////////////////////////////////
  //类事件的处理代码如下
  private void SendMsgTest()
  {
   //创建ChatServer类的实例
   Server f_Server;
   f_Server = new Server();
   f_Server.onSendMsg += new Server.MyEventHandler(this.OnSendMsg);
   //调用 f_Server的SendMsg()函数
   f_Server.SendMsg();
  }
  //处理 onSendMsg 事件代码
  protected void OnSendMsg(string msg)
  {
   //输出调试信息
   Console.WriteLine(msg);
  }

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-27
  • 2021-10-26
  • 2021-05-31
猜你喜欢
  • 2021-08-16
  • 2022-12-23
  • 2022-01-04
  • 2022-12-23
  • 2021-09-23
  • 2022-01-27
  • 2021-09-07
相关资源
相似解决方案