C#实现客户订餐的事件完整声明方式
1、我们应该声明一个customer的类作为订餐事件的拥有者,类中应该有Bill属性和PayTheBill方法;
2、然后我们应该声明一个waiter的类作为订餐事件的响应者;
3、应该自定义一个名为order的委托类型(在委托类型中我们应该定义一个customer的变量,和一个实参变量);
4、定义一个传递事件信息的类OrderEventArgs,将产品的信息定义出来;
5、作为基础的委托类型已经有了,我们来声明一个事件并写在customer里面,声明一个private委托类型的字段用来存储和引用事件处理器,再声明事件,声明一个事件处理器的添加器;
6、至此我们已经拥有了事件的其中三个部分,事件拥有者、事件响应者、事件,则我们应该在主函数中订阅这个事件,从而在waiter中添加事件处理器;
using System;
using System.Threading;
namespace EventSample_1_
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
Waiter waiter = new Waiter();
customer.Order += waiter.Action;
customer.Action();
customer.PayTheBill();
}
}
/*事件信息用事件名字+“EventArgs”来命名,用来传递事件消息的类*/
public class OrderEventArgs:EventArgs//规定某个类用途时用于"EventArgs"使用的话,就将这个类派生于“EventArgs”这个类
{
public string DishName { get; set; }//点的什么菜
public string Size { get; set; }//点的大份还是小份
}
/*委托是事件的底层基础,事件是委托的上层建筑
自定义声明一个委托类型,与类同级,如果一个委托是为了声明某个事件,这个委托将用“EventHandle”作为后缀
customer点菜将设为第一个参数
第二个参数用来存取菜名信息*/
public delegate void OrderEventHandler(Customer customer, OrderEventArgs e);
/*“EventHandle的用意有三:”
1、这个委托专门用来声明事件的
2、表明了用来约束事件处理器的
3、这个委托未来创建出来的实例时专门存储事件处理器的*/
/*事件的拥有者Customer
调整访问级别为Public
保持访问级别一致*/
public class Customer
{
private OrderEventHandler orderEventHandle;//声明一个private字段,用来存储和引用事件处理器的
public event OrderEventHandler Order//声明事件
{
add//事件处理器的添加器
{
this.orderEventHandle += value;//加入从外界传入的EventHandle
}
remove
{
this.orderEventHandle -= value;//事件处理器的移除器
}
}
public double Bill { get; set; }//记录用户在点菜方面花了多少钱
public void PayTheBill()//方法,打印用户将要支付多少钱
{
Console.WriteLine("I will pay ${0}",this.Bill);
}
/*为customer添加方法*/
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`s me think ...");
Thread.Sleep(1000);
}
if (this.orderEventHandle!=null)//检查事件是否为空
{
OrderEventArgs e = new OrderEventArgs();
e.DishName = "Kongpao Chicken";
e.Size = "large";
this.orderEventHandle.Invoke(this, e);//调用参数
}
}
public void Action()
{
Console.ReadLine();
this.WalkIn();
this.SitDown();
this.Think();
}
}
public 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;
default:
break;
}
customer.Bill += price;
}
}
}