敲了一遍代码,刘老师太厉害了,例子栩栩如生啊
namespace LiuTeacher
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
Waiter waiter = new Waiter();
//事件订阅者,也可以先写这里进行系统反生成
customer.Order += waiter.Action;
customer.ActionAll();
customer.PayTheBill();
}
}
//声明数据类型,来做菜单信息
public class OrderEventArgs : EventArgs
{
public string DishName { get; set; }
public string Size { get; set; }
}
//委托声明(点菜人,菜单信息)
public delegate void OrdersEventHandler(Customer customer, OrderEventArgs e);
//事件拥有者
public class Customer
{
//声明一个委托字段,用来存储事件处理器
private OrdersEventHandler orderEventHandler;
//声明事件
public event OrdersEventHandler Order
{
add
{
this.orderEventHandler += value;
}
remove
{
this.orderEventHandler -= value;
}
}
public double Bill { get; set; }
public void PayTheBill()
{
Console.WriteLine("我要付钱{0}元", this.Bill);
}
public void WalkIn()
{
Console.WriteLine("走进饭店");
}
public void SitDown()
{
Console.WriteLine("坐下");
}
public void Think()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("让我想一想");
Thread.Sleep(1000);
}
if (this.orderEventHandler!=null)
{ OrderEventArgs e = new OrderEventArgs();
e.DishName = "宫保鸡丁";
e.Size = "large";
this.orderEventHandler.Invoke(this, e);
}
}
public void ActionAll()
{
Console.ReadLine();
this.WalkIn();
this.SitDown();
this.Think();
}
}
//事件订阅者,服务生
public class Waiter
{ //事件处理器
public void Action(Customer customer, OrderEventArgs e)
{
Console.WriteLine("服务员A:我将给你上菜--{0}",e.DishName);
double price = 20;
switch (e.Size)
{
case "small":
price = price * 0.5;
break;
case "large":
price = price *1.5;
break;
default:
break;
}
customer.Bill += price;
}
}
}