参考 刘铁猛《C#语言入门详解》
Final Example
using System;
using System.Threading;
//事件声明的完整方式
//事件的五个部分
//+ 事件的拥有者
//+ 事件
//+ 事件的响应者
//+ 事件的处理器
//+ 事件的订阅
//参考 --- 刘铁猛《C#语言入门详解》全集
namespace Event
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
Waiter waiter = new Waiter();
customer.Order += waiter.Action;
customer.Action();
customer.PayTheBill();
}
}
public class Waiter
{
public void Action(object sender, EventArgs e)
{
Customer customer = sender as Customer;
OrderEventArgs orderInfo = e as OrderEventArgs;
Console.WriteLine("I will serve you the dish - {0}", orderInfo.DishName);
double price = 10;
switch (orderInfo.Size)
{
case "small":
price = price * 0.5;
break;
case "large":
price = price * 1.5;
break;
default:
break;
}
customer.Bill += price;
}
}
// [.Net] 传递事件信息的类 ,建议使用事件信息术语 EventArgs 作为后缀 , 派生自 EventArgs 类
public class OrderEventArgs : EventArgs
{
public string DishName { get; set; }
public string Size { get; set; }
}
public class Customer
{
// 编译后会自动生成委托类型字段 Order
public event EventHandler Order;
public double Bill { get; set; }
public void PayTheBill()
{
Console.WriteLine("I will pay ${0}", this.Bill);
}
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 me think ...");
Thread.Sleep(1000);
}
this.OnOrder("Chicken", "large");
}
// 使用protected保护方法
protected void OnOrder(string dishName , string size)
{
if (this.Order != null)
{
OrderEventArgs e = new OrderEventArgs();
e.DishName = dishName;
e.Size = size;
// 事件触发
this.Order.Invoke(this, e);
}
}
public void Action()
{
Console.ReadLine();
this.WalkIn();
this.SitDown();
this.Think();
}
}
}