c#自定义事件(详细定义的例子)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace ConsoleApp13
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer();//事件拥有者
            Waiter waiter = new Waiter();//事件响应者
            customer.Ooder += waiter.Action;//事件订阅
            customer.Action();
            

        }

  
    }
    public class OrderEventArgs : EventArgs
    {
        public string DishName { get; set; }
        public string DishSize { get; set; }
    }

    public delegate void OrderSEventHandler(Customer customer, OrderEventArgs e);

    public class Customer
    {
        private OrderSEventHandler orderSEventHandler;//委托字段(引用事件处理器)
        public event OrderSEventHandler Ooder //声明事件
        {
            add
            {
                this.orderSEventHandler += value;
            }
            remove
            {
                this.orderSEventHandler -= value;
            }
        }
        public Double bill { get; set; }

        public void WakeIn()
        {
            Console.WriteLine("I am wake in");
        }
        public void SitDown()
        {
            Console.WriteLine("I am sit down");
        }
        public void Think()
        {
            for(int i = 0;i < 5; i++)
            {
                Console.WriteLine("I am think...");
                Thread.Sleep(1000);
            }
            if(this.orderSEventHandler!=null)
            {
                OrderEventArgs e = new OrderEventArgs();
                e.DishName = "Chicken";
                e.DishSize = "small";
                Console.WriteLine("I want a {0}",e.DishName);
                
                this.orderSEventHandler.Invoke(this,e);
            }
        }
        public void paybill()
        {
            Console.WriteLine("I will pay {0}",bill);
        }
        public void Action()
        {
            Console.ReadLine();

            this.WakeIn();
            this.SitDown();
            this.Think();
            this.paybill();
        }
        
    }
    public class Waiter
    {
        internal void Action(Customer customer, OrderEventArgs e)
        {
            Console.WriteLine("I will sever {0}",e.DishName);
            double price = 10;
            switch(e.DishSize)
            {
                case "small": price = price * 0.5;
                    break;
                case "large": price = price * 1.5;
                    break;
                default:
                    break;
            }
            customer.bill += price;
            Console.WriteLine("You will pay {0}",price);

        }
    }
}


版权声明:本文为weixin_68861604原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。