事件于委托
一、事件
(1)需要一个表示时间参数的对象
class BallEventArgs:EventArgs
{
public int Trajectory{get; private set;}
public int Distence{get; private set;}
public BallEventArgs(int Trajectoty, int Distence){
this.Trajectory = Trajectory;
this.Distence = Distence;
}
}
(2)在产生事件的类专用定义这个事件
//产生事件的类
class Ball
{
//定义事件
//EventHandler告诉事件订购对象它的事件处理方法应该是什么样的
public event EventHandler BallInPlay;
//产生事件
public void OnBallInPlay(BallEventArgs e){
if (BallInPlay != null)
BallInPlay(this,e);
}
}
(3)订购类需要处理事件的方法,各个对象订购事件
class Pitcher
{//订购事件
public Pitcher(Ball ball) {
ball.BallInPlay += new EventHandler(ball_BallInPlay);
}
//事件处理程序
void ball_BallInPlay(object sender, EventArgs e) {
if (e is BallEventArgs) {
BallEventArgs ballEventArgs = e as BallEventArgs;
if (ballEventArgs.Distence < 95 && ballEventArgs.Trajectory < 60)
CatchBall();
else
CoverFirstBase();
}
}
private void CatchBall() {
MessageBox.Show("Pitcher: I catch the ball!");
}
private void CoverFirstBase(){
MessageBox.Show("Pitcher: I cover first base!");
}
}
(4)测试
public partial class Form1 : Form
{
Ball ball = new Ball();
Pitcher pitcher;
public Form1()
{
InitializeComponent();
pitcher = new Pitcher(ball);
}
private void button1_Click(object sender, EventArgs e)
{
BallEventArgs ballEventArgs = new BallEventArgs((int)numericUpDown1.Value, (int)numericUpDown2.Value);
ball.OnBallInPlay(ballEventArgs);
}
}