简单的事件示例代码:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Timers; namespace ConsoleAppTestDemo1 { public delegate void OrdereventHandler(Customer customer, OrderEventArgs e); public class OrderEventArgs : EventArgs { public string DishName { get; set; } public string Size { get; set; } } public class Customer { private OrdereventHandler ordereventHandler; public event OrdereventHandler Order { add { this.ordereventHandler += value; } remove { this.ordereventHandler -= value; } } public double Bill { get; set; } public void PayTheBill() { Console.WriteLine($"I will pay ${this.Bill}"); } public void WalkIn() { Console.WriteLine("Wakl into the restaurant."); } public void SiteDown() { 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.ReadLine(); this.WalkIn(); this.SiteDown(); this.Think(); } } public class Waiter { public void Action(Customer customer, OrderEventArgs e) { Console.WriteLine($"I will server you then dish - {e.DishName} {e.Size}"); 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; } } class TestDemo1 { static void Main(string[] args) { Customer customer = new Customer(); Waiter waiter = new Waiter(); customer.Order += waiter.Action; customer.Action(); customer.PayTheBill(); Console.ReadLine(); } } }
输出信息:
Wakl into the restaurant. Sit down Let me think Let me think Let me think Let me think Let me think I will server you then dish - Kongpao Chicken large I will pay $15 请按任意键继续. . .
============ End
原文:https://www.cnblogs.com/lsgxeva/p/10502529.html