方法一,详细的声明
cs
namespace HelloWorldConsole
{
internal class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
Waiter waiter = new Waiter();
customer.Order += waiter.Action;
customer.Action();
}
}
public class OrderEventArgs : EventArgs
{
public string DishName { get; set; }
public string Size { get; set; }
}
public delegate void OrderEventHandler(Customer customer, OrderEventArgs e);
public class Customer
{
public double Bill { get; set; }
private OrderEventHandler orderEventHandler;
public event OrderEventHandler Order
{
add { orderEventHandler += value; }
remove { orderEventHandler -= value; }
}
public void PayTheBill()
{
Console.WriteLine("i will pay-{0}", Bill);
}
public void Think()
{
if (orderEventHandler != null)
{
OrderEventArgs e = new OrderEventArgs();
e.DishName = "宫保鸡丁";
e.Size = "large";
orderEventHandler(this, e);
}
}
public void Action()
{
Think();
PayTheBill();
}
}
public class Waiter
{
public void Action(Customer customer, OrderEventArgs e)
{
double price = 10;
switch (e.Size)
{
case "small": price /= 2; break;
case "large": price *= 1.5; break;
default: break;
}
Console.WriteLine("i will serve the dish {0}-{1}", e.DishName, e.Size);
customer.Bill += price;
}
}
}
方法二,简化的声明,也是最常用的写法
cs
namespace HelloWorldConsole
{
internal class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
Waiter waiter = new Waiter();
customer.Order += waiter.Action;
customer.Action();
}
}
/// <summary>
/// 事件参收
/// </summary>
public class OrderEventArgs : EventArgs
{
public string DishName { get; set; }
public string Size { get; set; }
}
public class Customer
{
public double Bill { get; set; }
public event EventHandler Order;
public void Think()
{
if (Order != null)
{
OrderEventArgs e = new OrderEventArgs();
e.DishName = "宫保鸡丁";
e.Size = "large";
Order(this, e);
}
}
public void PayTheBill()
{
Console.WriteLine("i will pay-{0}", Bill);
}
public void Action()
{
Think();
PayTheBill();
}
}
public class Waiter
{
public void Action(object sender, EventArgs _e)
{
Customer customer = sender as Customer;
OrderEventArgs e = _e as OrderEventArgs;
double price = 10;
switch (e.Size)
{
case "small": price /= 2; break;
case "large": price *= 1.5; break;
default: break;
}
Console.WriteLine("i will serve the dish {0}-{1}", e.DishName, e.Size);
customer.Bill += price;
}
}
}