完整版:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EventLearning2 { class Program { static void Main(string[] args) { Customer customer = new Customer();//事件拥有者 Waiter waiter = new Waiter();//事件响应者 customer.Order += waiter.Action;//Order是事件,事件的订阅,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 { public double Bill { get; set; } private OrderEventHandler orderEventHandler;//委托字段 public event OrderEventHandler Order//声明事件 { add { this.orderEventHandler += value;//事件添加器,加等于外界传进来的事件处理器 } remove { this.orderEventHandler -= value; } } public void PayTheBill() { Console.WriteLine("I will pay {0}",this.Bill); } public void WalkIn() { Console.WriteLine("I walk in the restaurant"); } public void SitDown() { Console.WriteLine("I sit down"); } public void Think() { for (int i = 0; i < 5; i++) { Console.WriteLine("Let me think..."); Thread.Sleep(500); } if (this.orderEventHandler!=null) { OrderEventArgs e = new OrderEventArgs(); e.DishName = "ShuanYangRou"; e.Size = "large"; this.orderEventHandler.Invoke(this, e); } } public void Action() { Console.ReadLine(); this.WalkIn(); this.SitDown(); this.Think(); } } public class Waiter { internal 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 = price * 0.5; break; case "large": price = price * 1.5; break; default: break; } customer.Bill += price; } } }
简化声明: