文章目录
概要
事件是C#中的一个看似简单其实又比较难的点,这个代码是如何自己创一个事件,而不是用C#中自带的事件
整体架构流程
技术名词解释
技术细节
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace 自定义事件
{
internal 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 OrderEventArgs:EventArgs
{
public string DishName { get; set; }
public string Size { get; set; }
}
public delegate void OrderEventHandler(Customer customer, OrderEventArgs e);
public class Customer
{
private OrderEventHandler orderEventHandler;
public event OrderEventHandler Order
{
add { orderEventHandler += value; }
remove { orderEventHandler -= value; }
}
public double Bill { get; set; }
public void PayTheBill()
{
Console.WriteLine("I will pay ${0}",this.Bill);
}
public void walkin()
{
Console.WriteLine("walk in the restaurant");
}
public void Sitdowen()
{
Console.WriteLine( "sit down");
}
public void Think()
{
for(int i = 0;i<5; i++)
{
Console.WriteLine( "Let me think");
Thread.Sleep(1000);
}
if(this.orderEventHandler != null)
{
OrderEventArgs e = new OrderEventArgs();
e.DishName = "kongpao chicken";
e.Size = "large";
this.orderEventHandler.Invoke(this, e);
}
}
public void Action()
{
Console.WriteLine("请按回车!!!!!");
Console.ReadLine();
this.walkin();
this.Sitdowen();
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 = 10*0.5; break;
case "large":
price = 10*1.5; break;
default:
break;
}
customer.Bill += price;
}
}
}
小结
提示:这里可以添加总结
例如:
提供先进的推理,复杂的指令,更多的创造力。