2018年2月7日水曜日

開発環境

初めてのC# 第2版 (Jesse Liberty (著)、Brian MacDonald (著)日向 俊二 (翻訳)、オライリージャパン)の17章(デリゲートとイベント)、17.16(練習問題)、練習17-1.を取り組んでみる。

コード

using System;
using System.Threading;

namespace sample17_1
{
    class CountDownEventArgs: EventArgs
    {
        public readonly string message;
        public CountDownEventArgs(string message)
        {
            this.message = message;
        }
    }
    class CountDownPub
    {
        private DateTime start;
        private DateTime end;
        private string message;

        public delegate void Handler(object clock, CountDownEventArgs args);

        public CountDownPub(string message, int hours, int minutes, int seconds)
        {
            this.message = message;
            start = DateTime.Now;
            TimeSpan duration = new TimeSpan(hours, minutes, seconds);
            end = start + duration;
        }

        public Handler handler;

        public void Run()
        {
            for (;;)
            {
                Thread.Sleep(10);
                System.DateTime dt = System.DateTime.Now;

                if (dt >= end)
                {
                    CountDownEventArgs e = new CountDownEventArgs(message);
                    handler(this, e);
                    break;
                }
            }
        }
    }
    class CountDownSub
    {
        public void Display(object obj, CountDownEventArgs args)
        {
            Console.WriteLine(args.message);
        }
        public CountDownSub(CountDownPub pub)
        {
            CountDownPub.Handler handler = new CountDownPub.Handler(Display);
            pub.handler += handler;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Message: ");
            string msg = Console.ReadLine();
            Console.Write("seconds: ");
            int seconds = Convert.ToInt32(Console.ReadLine());

            CountDownPub pub = new CountDownPub(msg, 0, 0, seconds);
            CountDownSub sub = new CountDownSub(pub);
            pub.Run();
        }
    }
}

入出力結果(Terminal)

Message: Hello, World!
seconds: 5
Hello, World!

Press any key to continue...

0 コメント:

コメントを投稿