C# Event (事件)
之前我只寫過 UEFI 的事件,UEFI 的事件比 C# 簡單多了。C# Event 的重點在於 Handler, Callback and Listener。 Handler 處理事件的訂閱和 Callback,Callback 是事件觸發時要做的事,Listener 會監聽事件並捕獲事件。
下面的例子中 waiter 會通知客人去用餐,客人會等待被通知要吃午餐或晚餐。用餐的內容是一個等待被呼喚的事件,觸發事件時顧客也會取得用餐的資訊。
using System;
namespace DotNetCoreTest
{
class Program
{
// create a callback.
public class MealInfo : EventArgs
{
public MealInfo (string meal)
{
Meal = meal;
}
public string Meal { get; set; }
}
// Handle subscription and invoke the callback.
public class Waiter
{
public EventHandler MealIsReady;
public void InformCustomer(string meal)
{
MealIsReady?.Invoke(this, new MealInfo(meal));
}
}
// Listen to the event.
public class Customer
{
private string _name;
public Customer(string name)
{
Name = name;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
// Linsten to an event.
public void EatMeal(object waiter, MealInfo e)
{
Console.WriteLine($"{_name} is informed to have a {e.Meal}");
}
}
static void Main(string[] args)
{
var waiter = new Waiter();
var Bob = new Customer("Bob");
var Alice = new Customer("Alice");
// Subscribe the event.
waiter.MealIsReady += Bob.EatMeal;
waiter.MealIsReady += Alice.EatMeal;
// Trigger event.
waiter.InformCustomer("lunch");
waiter.InformCustomer("dinner");
}
}
}
留言
張貼留言