c#用委托来实现事件通知机制。委托相当与c++函数指针。整个过程涉及一个呼叫者,一个被呼叫者,还有就是这个委托。
- 实现步骤
有以下几步: 1. 申明委托, 2.定义呼叫者和调用的函数, 3.定义被呼叫者和具体实现的函数(被调用的函数)
1.申明委托 ,在包里或者类里,public
public
delegate
void
PlayGame( Object sender, EventArgs e
);
2.定义呼叫者(类LetsGame)和调用委托的函数,在呼叫者里要有委托的实例(呼叫者扔出一个委托,被呼叫者给这个委托赋值)
class
LetsGame{
public event PlayGame theGame;
public void startPlay(EventArgs e){
if (theGame != null ){
theGame( this ,e);
}
}
public event PlayGame theGame;
public void startPlay(EventArgs e){
if (theGame != null ){
theGame( this ,e);
}
}
3. 定义被呼叫者(类MS)和具体实现的函数(被调用的函数),也就是concrete class的实现或者叫函数指针实例。打个比方,在一个叫MS的类中实现.MS中对呼叫者中委托的实例进行赋值.
class
MS {
public MS(LetsGame lg) {
lg.theGame += new PlayGame(MSPlayGame);
}
public void MSPlayGame(Object sender, EventArgs e){
Console.WriteLine( " Who laughs the last who wins " );
}
}
public MS(LetsGame lg) {
lg.theGame += new PlayGame(MSPlayGame);
}
public void MSPlayGame(Object sender, EventArgs e){
Console.WriteLine( " Who laughs the last who wins " );
}
}
这样当调用LetsGame.startPlay的时候就会调用MS.MSPlayGame.