|
using System;
using System.Threading;
namespace C井事件 {
class Program {
static void Main(string[] args) {
//自定义事件();//1,2系统内置参数事件
Customer customer = new Customer();
Waiter waiter = new Waiter();
customer.eventHandler += waiter.Action;//ctrl+. 然后敲回车(Action 事件处理器)
customer.Action();//事件拥有者的内部逻辑来触发事件
customer.PayTheBill();//最后买单结束
}
private static void 自定义事件() {
Customer customer = new Customer();
Waiter waiter = new Waiter();
customer.OrderEvent += waiter.Action;
customer.Action();
customer.PayTheBill();
}
}
//专门用来声明事件,表明约束事件处理器,未来创建出来的实例存储事件处理器
public delegate void OrderEventHandler(Customer customer, OrderEventArgs e);
public class Customer {
/*
private OrderEventHandler orderEventHandler;//用来引用事件处理器
public event OrderEventHandler OrderEvent {
add { orderEventHandler += value; }
remove { orderEventHandler -= value; }
}
*/
public event OrderEventHandler OrderEvent;//自定义的
public event EventHandler eventHandler;//系统内置
public double Bill { get; set; }
public void PayTheBill() {
Console.WriteLine($"I will pay ${Bill}");
}
public void WalkIn() {
Console.WriteLine("Walk into the 餐馆");
Thread.Sleep(1000);
Console.WriteLine("Sit down...");
}
public void Think() {
for (int i = 0; i < 5; i++) {
Console.WriteLine("Let me think ....");
Thread.Sleep(1000);
}
/*** S1 旧版
if (this.orderEventHandler != null) {//是否有服务员订阅该事件
OrderEventArgs e = new OrderEventArgs() { DishName = "宫保鸡丁",Size="small" };
this.orderEventHandler.Invoke(this, e);
}***/
if (this.OrderEvent != null) {//是否有服务员订阅该事件
OrderEventArgs e = new OrderEventArgs() { DishName = "自定义的参数", Size = "small" };
this.OrderEvent(this, e);
}
//内置事件
if (this.eventHandler != null) {//是否有服务员订阅该事件
OrderEventArgs e = new OrderEventArgs() { DishName = "eventArgs", Size = "large" };
this.eventHandler.Invoke(this, e);
}
}
public void Action() {
this.WalkIn();
this.Think();
}
}
public class Waiter {
internal void Action(Customer customer, OrderEventArgs e) {
//throw new NotImplementedException();
Console.WriteLine($"(自定义参数事件) I will server you the dish {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;
}
internal void Action(object sender, EventArgs eventArgs) {
Customer customer = sender as Customer;
OrderEventArgs e = eventArgs as OrderEventArgs;
Console.WriteLine($"(EventArgs参数事件)I will server you the dish {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;
}
}
public class OrderEventArgs:EventArgs {
public string DishName { get; set; }//菜名
public string Size { get; set; }//大小份
}
}
|
|