c#语言入门详解022事件详解学习记录

敲了一遍代码,刘老师太厉害了,例子栩栩如生啊

namespace LiuTeacher
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer();
            Waiter waiter = new Waiter();
            //事件订阅者,也可以先写这里进行系统反生成
            customer.Order += waiter.Action;
            customer.ActionAll();
            customer.PayTheBill();
        }
    }
    //声明数据类型,来做菜单信息
    public class OrderEventArgs : EventArgs
    {
        public string DishName { get; set; }
        public string Size { get; set; }
    }
    //委托声明(点菜人,菜单信息)
    public delegate void OrdersEventHandler(Customer customer, OrderEventArgs e);
    //事件拥有者
    public class Customer
    {
        //声明一个委托字段,用来存储事件处理器
        private OrdersEventHandler orderEventHandler;
        //声明事件
        public event OrdersEventHandler Order
        {
            add
            {
                this.orderEventHandler += value;
            }
            remove
            {
                this.orderEventHandler -= value;
            }
        }
        public double Bill { get; set; }
        public void PayTheBill()
        {
            Console.WriteLine("我要付钱{0}元", this.Bill);
        }
        public void WalkIn()
        {
            Console.WriteLine("走进饭店");
        }
        public void SitDown()
        {
            Console.WriteLine("坐下");
        }
        public void Think()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("让我想一想");
                Thread.Sleep(1000);
            }
            if (this.orderEventHandler!=null)
            { OrderEventArgs e = new OrderEventArgs();
                e.DishName = "宫保鸡丁";
                e.Size = "large";
                this.orderEventHandler.Invoke(this, e);
            }
        }
        public void ActionAll()
        {
            Console.ReadLine();
            this.WalkIn();
            this.SitDown();
            this.Think();
        }
    }
    //事件订阅者,服务生
    public class Waiter
    {    //事件处理器
        public void Action(Customer customer, OrderEventArgs e)
        {
            Console.WriteLine("服务员A:我将给你上菜--{0}",e.DishName);
            double price = 20;
            switch (e.Size)
            {
                case "small":
                    price = price * 0.5;
                    break;
                case "large":
                    price = price *1.5;
                    break;
                default:
                    break;
            }
            customer.Bill += price;
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值