2012年6月27日水曜日

開発環境

『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第17章(デリゲートとイベント)17.6(練習問題)、問題17-2を解いてみる。

問題 17-2

コード

using System;
using System.Threading;

namespace Sample
{
    public class TimeInfoEventArgs : EventArgs
    {
        private string message;
        public TimeInfoEventArgs(string message)
        {
            this.message = message;
        }
        public string Message
        {
            get { return message; }
        }
    }
    public class Clock
    {
        private DateTime start;
        private DateTime stop;
        private string message;
        public Clock(int hour, int minute, int second, string message)
        {
            start = DateTime.Now;
            TimeSpan duration = new TimeSpan(hour, minute, second);
            stop = start + duration;
            this.message = message;
        }
        public delegate void SecondChangeHandler
            (object clock, TimeInfoEventArgs ti);
        public SecondChangeHandler SecondChanged;
        public void Run()
        {
            for (int i = 0; ; i++)
            {
                Console.Write("{0}秒 ", i);
                Thread.Sleep(1000);
                DateTime dt = DateTime.Now;
                if (dt >= stop)
                {
                    TimeInfoEventArgs ti =
                        new TimeInfoEventArgs(message);
                    if (SecondChanged != null)
                    {
                        Console.WriteLine();
                        SecondChanged(this, ti);
                        break;
                    }
                }
            }
        }
    }
    public class DisplayClock
    {
        public void Subscribe(Clock clock)
        {
            // 「+=」ではなく「=」に変更
            clock.SecondChanged =
                new Clock.SecondChangeHandler(TimeHasChanged);
        }
        public void TimeHasChanged(object clock, TimeInfoEventArgs ti)
        {
            Console.WriteLine(ti.Message);
        }
    }
    class Tester
    {
        public void Run()
        {
            Console.WriteLine("通知する経過時間(時、分、秒)を入力");
            int hour = Convert.ToInt16(Console.ReadLine());
            int minute = Convert.ToInt16(Console.ReadLine());
            int second = Convert.ToInt16(Console.ReadLine());
            Console.WriteLine("メッセージを入力");
            string message = Console.ReadLine();
            Clock clock = new Clock(hour, minute, second, message);
            DisplayClock dc = new DisplayClock();
            dc.Subscribe(clock);
            clock.Run();
        }
        static void Main()
        {
            Tester t = new Tester();
            t.Run();
        }
    }
}

入出力結果(Console Window)

通知する経過時間(時、分、秒)を入力
0
0
10
メッセージを入力
Hello, World!
0秒 1秒 2秒 3秒 4秒 5秒 6秒 7秒 8秒 9秒
Hello, World!
続行するには何かキーを押してください . . .

0 コメント:

コメントを投稿