C#委托与事件
C#中委托与事件的基本使用方法:
//定义委托模板
Public delegate void ReceiveMsgEventHandled(object sender,clsTcpMsgEventArgs e);
//定义事件
private event ReceiveMsgEventHandler ReceiveMsgEvent;
//公有事件,注册事件
Public event ReceiveMsgEventHandler e_ReceiveMsgEvent
{
add
{ReceiveMsgEvent=(ReceiveMsgEventHandler)System.Delegate.Combine(ReceiveMsgEvent , value);}
remove
{ReceiveMsgEvent=(ReceiveMsgEventHandler)System.Delegate.Remove(ReceiveMsgEvent , value);}
}
//执行事件,方法体
Private void m_ReceiveMsg(string strMessage)
{
clsTcpMsgEventArgs e=new clsTcpMsgEventArgs(strMessage);//创建事件消息对象
if(ReceiveMsgEvent!=null)
ReceiveMsgEvent(this,e);//执行事件
}
//调用此事件
//1.声明,实例对象
clsTcpClient myTcpClient=new clsTcpClient();//此类中包含上面的事件
//2.注册调用事件方法
myTcpClient.e_ReceiveMsgEvent += new clsTcpClient.ReceiveMsgEventHandle(m_ReceiveMsg);
//3.事件执行的方法体
Private void m_ReceiveMsg(object sender,clsTcpMsgEventArgs e)
//事件消息类
Public Class clsTcpMsgEventArgs : EventArgs //继承至EventArgs
{
Public readonly string strTcpMsg;//只读,传递消息
Public clsTcpMsgEventArgs(string TcpMsg)
this.strTcpMsg=TcpMsg;
}