C#イベントメカニズム学習ノート

2808 ワード

C#タイムメカニズム学習
イベント宣言:public eventエージェント名イベント名;
C#ではdelegateを使用することで、イベントに「+=」で1つ以上の応答メソッドを追加できます.「-=」を使用して、これらのメソッドをキャンセルします.
C#でイベントを使用するには:
1、依頼を作成します.
2作成された依頼を特定のイベントに関連付ける.
3、イベントハンドラの作成;
4、作成したイベントハンドラを利用して依頼例を生成する.
5,この依頼インスタンスをイベントオブジェクトを生成するイベントリストに追加する(イベントを購読する).
6,プログラムを作成してイベントの発生をトリガする.
イベントインスタンス:
キーボード入力イベントをキャプチャし、1文字を入力するたびにコンソールから大文字で出力します.
【運転環境:VS 2008】

using System;
using System.Collections.Generic;
using System.Text;

namespace StudyEvent2
{
    class Program
    {
        static void Main(string[] args)
        {
            KeyInputMonitor monitor = new KeyInputMonitor();
            EventReceiver receiver = new EventReceiver(monitor);

            monitor.Run();
            //Console.ReadKey();
        }
    }

    internal class KeyEventArgs : EventArgs
    {
        private char keyChar;

        public KeyEventArgs(char keyChar) : base()
        {
            this.keyChar = keyChar;
        }

        public char KeyChar
        {
            get
            {
                return this.keyChar;
            }
        }
    }

    internal class KeyInputMonitor
    {
        public delegate void KeyDown(object sender, KeyEventArgs e);

        public event KeyDown OnKeyDown;

        public void Run()
        {
            bool finished = false;

            do
            {
                Console.WriteLine("Input a char");
                string response = Console.ReadLine();

                char responseChar = (response == "") ? ' ' : char.ToUpper(response[0]);

                switch (responseChar)
                {
                    case 'X':
                        finished = true;
                        break;
                    default:
                        KeyEventArgs keyEventArgs = new KeyEventArgs(responseChar);
                        OnKeyDown(this, keyEventArgs);
                        break;
                }
            } while (!finished);
        }
    }

    internal class EventReceiver
    {
        public EventReceiver(KeyInputMonitor monitor)
        {
            monitor.OnKeyDown += new KeyInputMonitor.KeyDown(Echo);
        }

        private void Echo(object sender, KeyEventArgs e)
        {
            Console.WriteLine("Capture key: {0}", e.KeyChar);
        }
    }
}