開発環境
- OS: Windows 10 Pro
- IDE(統合開発環境): Visual Studio Community 2017
Head First C# ―頭とからだで覚えるC#の基本 (Andrew Stellman (著)、Jennifer Greene (著)、佐藤 嘉一 (監修, 監修)、木下 哲也 (翻訳)、オライリージャパン)の9章(イベントとデリゲート - 見ていないときのコードの動作)、エクササイズ(p. 390)を取り組んでみる。
コード
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 WindowsFormsApp22 { public partial class Form1 : Form { Ball ball; Pitcher pitcher; Fan fan; public Form1() { InitializeComponent(); ball = new Ball(); pitcher = new Pitcher(ball); fan = new Fan(ball); } private void button1_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); } private void CatchBall() { Console.WriteLine("ピッチャー: ボールを捕った。"); } private void CoverFirstBase() { Console.WriteLine("ピッチャー: ファーストをカバーする。"); } void ball_BallInPlay(object sender, EventArgs e) { if (e is BallEventArgs) { BallEventArgs ballEventArgs = e as BallEventArgs; if ((ballEventArgs.Distance < 95) && (ballEventArgs.Trajectory < 60)) { CatchBall(); } else { CoverFirstBase(); } } } } 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; if (ballEventArgs.Distance > 40 && ballEventArgs.Trajectory > 30) { Console.WriteLine("ファン: ホームラン!ボールを捕りに行くぞ!"); } else { Console.WriteLine("ファン: ウォー ヒュー! イエー!"); } } } } }
0 コメント:
コメントを投稿