之前看过刘铁猛老师视频关于C#中事件的讲解,感觉受益匪浅,将视频中的演示的示例放在这里,便于以后的学习。
事件5要素:
1、发布者
2、订阅者
3、事件的声明
4、事件的注册/事件的订阅
5、事件的触发
namespace EventExercise { class Program { static void Main(string[] args) { Customer customer = new Customer(); Waiter waiter = new Waiter(); customer.Order += waiter.Action;//5、事件的注册 customer.OrderDish(); customer.PayTheBill(); } } //1、发布者 public class Customer { public event EventHandler Order;//3、事件声明 public double bill; public void PayTheBill() { Console.WriteLine("I will pay the ${0}.", this.bill); } public void OrderDish() { Console.WriteLine("I walk into a restaurant,and sit down."); for (int i = 0; i < 5; i++) { Console.WriteLine("let me think..."); Thread.Sleep(1000); } OrderEventArgs orderInfo = new OrderEventArgs() { DishName = "yuxiang rousi", Size = "big" }; this.Order(this, orderInfo);//4、事件的触发 } } public class OrderEventArgs :EventArgs { public string DishName { get; set; } public string Size { get; set; } } //2、订阅者 public class Waiter { public void Action(object sender, EventArgs e) { Customer customer = sender as Customer; OrderEventArgs orderInfo = e as OrderEventArgs; double price = 10; switch (orderInfo.Size) { case "small": price -= 5; break; case "big": price += 5; break; default: break; } Console.WriteLine("I will serve you dish<{0}>.", orderInfo.DishName); customer.bill += price; } } }
//事件的触发