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

namespace EventHandlerTest
{

        /*          -----------------事件------------
         * 利用敲门事件来说明下:
         *     有人按门铃,这是一个事件发布者
         *     主人听到门铃响后,去开门,这是一个响应事件的动作,是事件订阅者
         *     门铃这是事件信息的对象,把事件发布者和事件订阅者联系起来。
         */


        /// <summary>
        ///    事件发布者类
        /// </summary>
        public class Guest
        {
                public event EventHandler<RingEventArgs> RingBell;        //EventHandler 泛型委托
                                                                                                                            //系统自定义有两个参数: sender    类型:System.Object    事件源。    
                                                                                                                            //     e         类型:TEventArgs         包含事件数据的 EventArgs
                public void KnockDoor()
                {
                        if (RingBell != null)
                        {
                                Console.WriteLine("有人按了一次门铃。");
                                RingBell(this, new RingEventArgs(true));         //触发事件
                        }
                }
        }
        /// <summary>
        ///    事件信息的对象类
        /// </summary>
        public class RingEventArgs : EventArgs
        {
                private bool ring = false;

                public bool Ring
                {
                        get { return ring; }
                        set { ring = value; }
                }

                public RingEventArgs(bool ring)
                {
                        this.ring = ring;
                }


        }

        /// <summary>
        ///    事件订阅者类
        /// </summary>
        public class Master
        {
                /// <summary>
                /// 主人开门的方法
                /// 注意方法的参数声明
                /// 必须与RingBell事件签名相符
                /// </summary>
                /// <param name="sender">事件源</param>
                /// <param name="args">包含事件数据的 EventArgs</param>
                public void OpenDoor(object sender,RingEventArgs args)
                {
                        Thread.Sleep(3000);
                        Console.WriteLine("听到门铃响,过了3秒钟,主人去开门。");
                }
        }


        public class Test
        {

                private static void Main(string[] args)
                {
                        Guest guest = new Guest();                     //客人对象
                        Master master = new Master();                //主人对象
                        guest.RingBell += master.OpenDoor;     //注册事件方法
                        guest.KnockDoor();                                     //客人敲门

                        Console.Read();
                }
        }

}