C#自定义事件案例

文章目录

概要

事件是C#中的一个看似简单其实又比较难的点,这个代码是如何自己创一个事件,而不是用C#中自带的事件

整体架构流程

技术名词解释

技术细节

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 自定义事件
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer();//事件拥有者
            Waiter waiter = new Waiter();//事件响应者
            customer.Order += waiter.Action;//事件
            customer.Action();
            customer.PayTheBill();
        }
    }
    public class OrderEventArgs:EventArgs 
    {
        public string DishName { get; set; }
        public string Size { get; set; }
    }
    public delegate void OrderEventHandler(Customer customer, OrderEventArgs e);

    public class Customer
    {
        private OrderEventHandler orderEventHandler;

        public event OrderEventHandler Order
        {
            add    { orderEventHandler += value; }
            remove { orderEventHandler -= value; }
        }
        public double Bill { get; set; }
        public void PayTheBill() 
        {

            Console.WriteLine("I will pay ${0}",this.Bill);

        }
        public void walkin()
        {
            Console.WriteLine("walk in the restaurant");
            
        }
        public void Sitdowen()
        {
            Console.WriteLine( "sit down");
        }
        public void Think()
        {
            for(int i = 0;i<5; i++)
            {
                Console.WriteLine(  "Let me think");
                Thread.Sleep(1000);
            }
            if(this.orderEventHandler != null)
            {
                OrderEventArgs e = new OrderEventArgs();
                e.DishName = "kongpao chicken";
                e.Size = "large";
                this.orderEventHandler.Invoke(this, e);
            }
        }
        public void Action()
        {
            Console.WriteLine("请按回车!!!!!");
            Console.ReadLine();
            
            this.walkin();
            this.Sitdowen();
            this.Think();
        }
    }

    public class Waiter
    {
      public void Action(Customer customer, OrderEventArgs e) //事件处理器
        {
            Console.WriteLine("I will serve you the dish-{0}",e.DishName);

            double price = 10;
            switch(e.Size)
            {
                case "small":
                    price = 10*0.5; break;
                case "large":
                    price = 10*1.5; break;
                default:
                    break;
            }
            customer.Bill += price;
      }
    }


}
 

小结

提示:这里可以添加总结

例如:

提供先进的推理,复杂的指令,更多的创造力。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值