1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| using System; using System.Threading;
namespace WholeEventDefinition { class Program { static void Main(string[] args) { var customer = new Customer(); var 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 { this.orderEventHandler += value; } remove { this.orderEventHandler -= value; } } public double Bill { get; set; } public void PayTheBill() { Console.WriteLine($"I will pay ${this.Bill}"); } public void WalkIn() { Console.WriteLine("Walk into the restaurant"); } public void SitDown() { 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) { var e = new OrderEventArgs {DishName = "KongPao Chicken", Size = "large"}; this.orderEventHandler.Invoke(this, e); } }
public void Action() { Console.ReadLine(); this.WalkIn(); this.SitDown(); this.Think(); }
} 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 = price * 0.5; break; case "large": price = price * 1.5; break; }
customer.Bill += price; } }
}
|