事件的完整声明:(刘铁猛老师视频示例)
按照事件的5要素去写
using System;
using System.Threading;
namespace EventFullDeclaration
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
Waiter waiter = new Waiter();
customer.Order += waiter.Action;
customer.Action();
}
}
//declare a delegate type
public delegate void OrderEventHandler(Customer customer,OrderEventArgs e);
public class OrderEventArgs :EventArgs
{
public string DishName { get; set; }
public string Size { get; set; }
}
//Customer类 事件的拥有者 以及 事件成员
//触发事件由事件拥有者的内部逻辑触发
public class Customer
{
//声明一个委托类型的字段
private OrderEventHandler 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 you ${0}",this.Bill);
}
public void WalkIn()
{
Console.WriteLine("I 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(orderEventHandler != null)
{
OrderEventArgs e = new OrderEventArgs ();
e.DishName = "Pork";
e.Size = "large";
this.orderEventHandler (this , e);
this.orderEventHandler.Invoke(this, e);
}
}
public void Action()
{
this.WalkIn();
this.SitDown();
this.Think();
}
}
public class Waiter
{
//事件处理器
public void Action(Customer customer, OrderEventArgs e)
{
Console.WriteLine("I will sever you the dish : {0}",e.DishName );
double price = 10;
switch (e.Size )
{
case "large":
price *= 1.5;
break;
case "small":
price *= 0.5;
break;
default:
break;
}
customer.Bill += price;
}
}
}