Head First C#
頭とからだで覚えるC#の基本
(オライリージャパン)
Andrew Stellman (著), Jennifer Green (著)
佐藤 嘉一 (監修), 木下 哲也 (翻訳)
開発環境
- Microsoft Windows 8.1 Pro (VMware Fusion 6, OS X Mavericks - Apple) (OS)
- C# (プログラミング言語)
- Microsoft Visual Studio Express 2013 for Windows Desktop (統合開発環境, IDE)
Head First C#―頭とからだで覚えるC#の基本 (Andrew Stellman (著)、Jennifer Green (著)、佐藤 嘉一 (監修)、木下 哲也 (翻訳)、オライリージャパン)の9章(イベントとデリゲート: 見てないときのコードの動作)、エクササイズ(p.390)を解いてみる。
エクササイズ(p.390)
コード
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class baseball : Form
{
Ball ball = new Ball();
Pitcher pitcher;
Fan fan;
public baseball()
{
InitializeComponent();
pitcher = new Pitcher(ball);
fan = new Fan(ball);
}
private void play_Click(object sender, EventArgs e)
{
BallEventArgs ballEventArgs = new BallEventArgs((int)trajectory.Value,(int)distance.Value);
ball.OnBallInPlay(ballEventArgs);
}
}
public 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;
Console.WriteLine("球筋: {0}, 距離: {1}", ballEventArgs.Trajectory, ballEventArgs.Distance);
if ((ballEventArgs.Distance < 95) && (ballEventArgs.Trajectory < 60))
{
CatchBall();
}
else
{
CoverFirstBase();
}
}
}
public void CatchBall()
{
Console.WriteLine("ピッチャー: ボールを捕った。");
}
public void CoverFirstBase()
{
Console.WriteLine("ピッチャー: ファーストをカバーする。");
}
}
public class Fan
{
public Fan(Ball ball)
{
ball.BallInPlay += new EventHandler(ball_BallInPlay);
}
void ball_BallInPlay(object sender, EventArgs e)
{
if (e is BallEventArgs)
{
BallEventArgs ballEventArgs = e as BallEventArgs;
Console.WriteLine("球筋: {0}, 距離: {1}", ballEventArgs.Trajectory, ballEventArgs.Distance);
if ((ballEventArgs.Distance > 400) && (ballEventArgs.Trajectory > 30))
{
CatchBall();
}
else
{
Console.WriteLine("ファン: ウォー ヒュー! イエー!");
}
}
}
public void CatchBall()
{
Console.WriteLine("ファン: ホームラン!ボールを捕りに行くぞ!");
}
}
}
出力(コマンドプロンプト)
球筋: 20, 距離: 100 ピッチャー: ファーストをカバーする。 球筋: 20, 距離: 100 ファン: ウォー ヒュー! イエー! 球筋: 20, 距離: 50 ピッチャー: ボールを捕った。 球筋: 20, 距離: 50 ファン: ウォー ヒュー! イエー! 球筋: 50, 距離: 450 ピッチャー: ファーストをカバーする。 球筋: 50, 距離: 450 ファン: ホームラン!ボールを捕りに行くぞ!
0 コメント:
コメントを投稿