C#基础--可以快速理解事件机制的事件示例

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace EvenDemo

{

    /// <summary>

    /// 事件参数类,继承自EventArgs,包含事件信息

    /// </summary>

    public class DoorInfoEventArgs : EventArgs

    {

        /// <summary>

        /// 显示门状态信息

        /// </summary>

        public string doorInfo;



        /// <summary>

        /// 构造函数

        /// </summary>

        /// <param name="isOpen">是否打开门,true/false</param>

        public DoorInfoEventArgs(bool isOpen)

        {

            if (isOpen)

            {

                doorInfo = "门现在已经打开了!";

            }

            else

            {

                doorInfo = "门不能打开!";

            }

        }

    }



    /// <summary>

    /// 定义门代理

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e">事件信息</param>

    public delegate void OpenDoorEventHandler(object sender, DoorInfoEventArgs e);





    /// <summary>

    /// 事件类

    /// </summary>

    public class CommandDoor

    {

        /// <summary>

        /// 定义事件(即:创建代理对象)

        /// </summary>

        public event OpenDoorEventHandler openDoor;



        /// <summary>

        /// 定义触发事件的属性

        /// </summary>

        public bool IsOpen

        {

            set 

            {

                DoorInfoEventArgs myEven = new DoorInfoEventArgs(value);//事件参数

                openDoor(this, myEven);//调用事件代理

            }

        }

 

    }



    class Program

    {

        static void Main(string[] args)

        {

            //创建事件对象,并添加事件实现代理的实例化

            CommandDoor commandDoor = new CommandDoor();

            commandDoor.openDoor += new OpenDoorEventHandler(Door);



            //由设置属性的值触发事件

            Console.WriteLine("是否打开门?Y/N");

            char commandChar =(char) Console.Read();

            if (commandChar == 'Y')

            {

                commandDoor.IsOpen = true;

            }

            else

            {

                commandDoor.IsOpen = false;

            }

            Console.ReadKey();



        }



        /// <summary>

        /// 事件执行的方法

        /// </summary>

        /// <param name="source"></param>

        /// <param name="e"></param>

        public static void Door(object source, DoorInfoEventArgs e)

        {

            Console.WriteLine(e.doorInfo);

        }

    }

}

你可能感兴趣的:(事件机制)