//定义事件及对象 Ball ball = new Ball(); //绑定 Fan fan = new Fan(ball);//Fan对Ball的处理,Fan先绑定BallInPlay Pitcher pitcher = new Pitcher(ball);//Pitcher对Ball的处理,Pitcher后绑定BallInPlay BallEventArgs ballEventArgs = new BallEventArgs(60,80); //事件发生后Fan先响应,Pitcher后响应 ball.OnBallInPlay(ballEventArgs)
//1、定义产生事件的对象 classBall{ //2、定义事件 //无事件绑定对象时BallInPlay = null //事件执行顺序为事件绑定顺序 publicevent EventHandler BallInPlay; protectedvoidOnBallInPlay(BallEventArgs e){ //EventHandler ballInplay = BallInPlay; //3、事件发生 //事件发生后会执行BallInPlay的委托,具体的执行发放为事件监视者所委托的方法 BallInPlay(this, e); //if (ballInplay != null) // ballInplay(this,e); } } classPitcher{ publicPitcher(Ball ball){ //4、不同对象订购(绑定)事件 //当事件发生后执行ball_BallInPlay1方法 ball.BallInPlay += ball_BallInPlay1; } voidball_BallInPlay1(object sender, EventArgs e){ if (e is BallEventArgs){ BallEventArgs ballEventArgs = e as BallEventArgs; if (ballEventArgs.Distance < 95 && ballEventArgs.Traj < 60){ CatchBall(); }else GameOver(); } } voidCatchBall(){ } voidGameOver(){ } } classFan{ publicFan(Ball ball){ //4、不同对象订购(绑定)事件 //当事件发生后执行ball_BallInPlay2方法 ball.BallInPlay += new EventHandler(ball_BallInPlay2); } voidball_BallInPlay2(object sender, EventArgs e){ if (e is BallEventArgs){ BallEventArgs ballEventArgs = e as BallEventArgs; if (ballEventArgs.Distance > 400) CatchBall(); else Screm(); } } voidCatchBall(){ } voidScrem(){ } } //事件执行的参数 classBallEventArgs : EventArgs{ publicint Traj { get; privateset; }//击球角度 publicint Distance { get; privateset; }//飞行距离 publicBallEventArgs(int traj, int distance){ this.Traj = traj; this.Distance = distance; } }