using System;
class Program
{
static void Main()
{
var ball = new Ball();
var patcher = new Pitcher(ball);
ball.OnBallInPlay(new BallEventArgs(100, 200));
Console.ReadLine();
}
class BallEventArgs : EventArgs
{ // BallEventArgs class 繼承 EventArgs
public int Trajectory { get; private set; }
public int Distance { get; private set; }
public BallEventArgs(int Trajectory, int Distance)
{
this.Trajectory = Trajectory;
this.Distance = Distance;
}
}
class Ball
{
private EventHandler _ballInPlay;
// Ball class
public event EventHandler BallInPlay {
add
{
_ballInPlay += value;
}
remove
{
_ballInPlay -= value;
}
}
public void OnBallInPlay(BallEventArgs e)
{
_ballInPlay?.Invoke(this, e);// 觸發 BallInPlay 事件
}
}
class Pitcher
{ // Pitcher class
public Pitcher(Ball ball)
{
ball.BallInPlay += new EventHandler(ball_BallInPlay); // 訂閱 BallInPlay 事件
}
void ball_BallInPlay(object sender, EventArgs e)
{ // BallInPlay 事件處理方法
if (e is BallEventArgs)
{ // 判斷物件是否為 BallEventArgs 實體
BallEventArgs ballEventArgs = e as BallEventArgs; // 將物件由 EventArgs 轉型 BallEventArgs
if ((ballEventArgs.Distance < 95) && (ballEventArgs.Trajectory < 60))
Console.WriteLine(" CatchBall();");
else
Console.WriteLine(" CoverFirstBase();");
}
}
}
}
class Program
{
static void Main()
{
var ball = new Ball();
var patcher = new Pitcher(ball);
ball.OnBallInPlay(new BallEventArgs(100, 200));
Console.ReadLine();
}
class BallEventArgs : EventArgs
{ // BallEventArgs class 繼承 EventArgs
public int Trajectory { get; private set; }
public int Distance { get; private set; }
public BallEventArgs(int Trajectory, int Distance)
{
this.Trajectory = Trajectory;
this.Distance = Distance;
}
}
class Ball
{
private EventHandler _ballInPlay;
// Ball class
public event EventHandler BallInPlay {
add
{
_ballInPlay += value;
}
remove
{
_ballInPlay -= value;
}
}
public void OnBallInPlay(BallEventArgs e)
{
_ballInPlay?.Invoke(this, e);// 觸發 BallInPlay 事件
}
}
class Pitcher
{ // Pitcher class
public Pitcher(Ball ball)
{
ball.BallInPlay += new EventHandler(ball_BallInPlay); // 訂閱 BallInPlay 事件
}
void ball_BallInPlay(object sender, EventArgs e)
{ // BallInPlay 事件處理方法
if (e is BallEventArgs)
{ // 判斷物件是否為 BallEventArgs 實體
BallEventArgs ballEventArgs = e as BallEventArgs; // 將物件由 EventArgs 轉型 BallEventArgs
if ((ballEventArgs.Distance < 95) && (ballEventArgs.Trajectory < 60))
Console.WriteLine(" CatchBall();");
else
Console.WriteLine(" CoverFirstBase();");
}
}
}
}
沒有留言:
張貼留言