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;
}