開発環境
- Microsoft Windows 8 Pro 64bit 日本語 (OS)
- Microsoft Visual Studio Express 2012 for Windows Desktop (IDE)
- プログラミング言語: C#
『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487312-194-7)の 第17章(デリゲートとイベント)16.12(練習問題)練習17-1.を解いてみる。
その他参考書籍
練習17-1.
コード
using System;
using System.Threading;
class TimeInfoEventArgs : EventArgs
{
public readonly string msg;
public TimeInfoEventArgs(string msg)
{
this.msg = msg;
}
}
class Clock
{
private string msg;
private DateTime start;
private DateTime stop;
public Clock(string msg, int hours, int minutes, int seconds)
{
this.msg = msg;
start = DateTime.Now;
TimeSpan duration = new TimeSpan(hours, minutes, seconds);
stop = start + duration;
}
public delegate void SecondChangeHandler
(object clock, TimeInfoEventArgs ti);
public SecondChangeHandler SecondChanged;
public void Run()
{
for (int i = 1; ; i++)
{
Thread.Sleep(1000);
Console.WriteLine("{0}秒経過", i);
DateTime now = DateTime.Now;
if (now >= this.stop)
{
TimeInfoEventArgs ti = new TimeInfoEventArgs(msg);
if (SecondChanged != null)
{
SecondChanged(this, ti);
break;
}
}
}
}
}
class DisplayClock
{
public void Subscribe(Clock clock)
{
clock.SecondChanged += new Clock.SecondChangeHandler(TimeHasChanged);
}
public void TimeHasChanged(object clock, TimeInfoEventArgs ti)
{
Console.WriteLine(ti.msg);
}
}
class Tester
{
public void Run()
{
Console.Write("出力メッセージを入力: ");
string msg = Console.ReadLine();
Console.WriteLine("経過を通史してほしい時間");
Console.Write("時: ");
int hours = Convert.ToInt16(Console.ReadLine());
Console.Write("分: ");
int minutes = Convert.ToInt16(Console.ReadLine());
Console.Write("秒: ");
int seconds = Convert.ToInt16(Console.ReadLine());
Clock clock = new Clock(msg, hours, minutes, seconds);
DisplayClock dc = new DisplayClock();
dc.Subscribe(clock);
clock.Run();
}
static void Main()
{
Tester t = new Tester();
t.Run();
}
}
入出力結果(Console Window)
出力メッセージを入力: 10秒経過 経過を通史してほしい時間 時: 0 分: 0 秒: 10 1秒経過 2秒経過 3秒経過 4秒経過 5秒経過 6秒経過 7秒経過 8秒経過 9秒経過 10秒経過 10秒経過 続行するには何かキーを押してください . . .
0 コメント:
コメントを投稿