using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EventExample2
{
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 DishSize { get; set; }
}
public delegate void OrderEventHandler(Customer customer, OrderEventArgs orderEventArgs);
public class Customer
{
private OrderEventHandler orderEventHandler;
public event OrderEventHandler Order{
add
{
this.orderEventHandler += value;
}
remove
{
this.orderEventHandler -= value;
}
}
public string Bill { get; set; }
public void PayTheBill() {
Console.WriteLine("I will pay ${0}.",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("Thinking...");
Thread.Sleep(1000);
}
if (this.orderEventHandler != null)
{
OrderEventArgs e = new OrderEve
C#自定义事件的完整定义方法和简化方法
最新推荐文章于 2024-09-07 10:30:00 发布
本文详细介绍了C#中自定义事件的完整定义过程,包括事件拥有者、事件、事件参数、事件委托和事件反应器。通过实例展示了服务员Waiter类如何监听顾客Customer类的点菜事件Order。同时,讨论了C#中事件定义的简化语法可能带来的误解,指出在使用简化语法时,Order事件后只能跟随“+=”或“-=”,并在Customer类的Think方法中调用invoke方法可能引发的混淆。建议遵循将触发事件的方法命名为Onxxx形式的编程规范。
摘要由CSDN通过智能技术生成