C#关于委托与事件的例子

来源:互联网 发布:python开发一个软件 编辑:程序博客网 时间:2024/05/17 21:43

/// <summary>
    /// 事件的参数类
    /// </summary>
    public class EatEventArgs : EventArgs
    {
        public string hotelsName;
        public int moneyOut;
    }

    /// <summary>
    /// 事件的发送者
    /// </summary>
    public class Mastor
    {
        //声明一个委托
        public delegate void EatEventHandles(object sender, EatEventArgs e);
        //声明一个事件
        public event EatEventHandles EatEvent;

        //触发事件函数
        public void OnEatEvent(EatEventArgs e)
        {
            if (EatEvent != null)
            {
                EatEvent(this, e);
            }
        }

        //饿的时候执行‘触发函数’
        public void Hungry()
        {
            Console.WriteLine("主人说:饿了,要吃饭,地点老地方,消费金额老价钱");
            EatEventArgs e = new EatEventArgs();
            e.hotelsName = "鲍翅皇宫";
            e.moneyOut = 10000;
            OnEatEvent(e);
        }
    }

    /// <summary>
    /// 事件的处理者
    /// </summary>
    public class Servant
    {
        //构造函数
        public  Servant(Mastor mastor)
        {
            mastor.EatEvent += new Mastor.EatEventHandles(this.Arrange);
        }
        //委托的处理函数
        public void Arrange(object sender, EatEventArgs e)
        {
            //new Mastor().EatEvent+=new Mastor.EatEventHandles(Arrange);
            Console.WriteLine("主人稍等,我这就安排");
            System.Threading.Thread.Sleep(5000);
            Console.WriteLine();
            Console.WriteLine("主人,{0}饭店的{1}大餐已经安排好,请慢用……", e.hotelsName, e.moneyOut);
        }
    }

    /// <summary>
    /// 调用
    /// </summary>
    public class Test3
    {
        public static void Main()
        {
            //创建事件发送者的实例
            Mastor mastor = new Mastor();
            //创建事件处理者的实例
            Servant servant = new Servant(mastor);
            //将处理者与发送者关联起来
            //mastor.EatEvent += new Mastor.EatEventHandles(servant.Arrange);
            //事件发送者开始触发事件
            mastor.Hungry();

        }
    }

 

原创粉丝点击