C# 中的事件 遵循“发布--订阅”的设计模式。在这种模式中,一个类公布能够出现的事件,然后任意数量的类都可以订阅这个事件,一旦事件发生,运行环境就负责通知每个订户,告诉她们事件已经发生了。
namespace @event
{
class InventoryChangeEventArgs{
public InventoryChangeEventArgs(string sku, int change)
{
this.sku = sku;
this.change = change;
}
string sku;
int change;
public string Sku
{
get
{
return sku;
}
}
public int Change
{
get
{
return change;
}
}
}
class InventoryManager {
public delegate void InventoryChangeEventHandler(object source,InventoryChangeEventArgs e);
public event InventoryChangeEventHandler OnInventoryChangeHandler;
public void UpdateInventory(string sku, int change)
{
InventoryChangeEventArgs e = new InventoryChangeEventArgs(sku,change);
//检查事件是否有什么与方法OnInventoryChangeHandler方法相关的订户。如果有,实际事件被引发了。
if (OnInventoryChangeHandler != null)
OnInventoryChangeHandler(this, e);
}
}
class InventoryWatcher {
public InventoryWatcher(InventoryManager inventoryManager) {
this.inventoryManager = inventoryManager;
inventoryManager.OnInventoryChangeHandler += new InventoryManager.InventoryChangeEventHandler(OnInventoryChange); //与代表关联的方法
}
InventoryManager inventoryManager;
void OnInventoryChange(object source, InventoryChangeEventArgs e)//方法
{
int change = e.Change;
Console.WriteLine("{0}---{1}",e.Sku,e.Change);
}
}
class Program
{
static void Main(string[] args)
{
InventoryManager inventoryManager = new InventoryManager();
InventoryWatcher inventoryWatch = new InventoryWatcher(inventoryManager);
inventoryManager.UpdateInventory("ttttt",22);
inventoryManager.UpdateInventory("sssss",222);
}
}
}