using System; //发布者和管理者的一个典型的例子,适合做多线程的事件监听 namespace PublishedAndSubscriber { class InventoryChangeEventArgs:EventArgs //被监听的类,需要从EventArgs继承 { public InventoryChangeEventArgs(string sku, int change) { this.sku = sku; this.change = change; } string sku; public string Sku { get { return sku; } } int change; public int Change { get { return change; } } } class InventoryManager //事件监听管理器,添加事件处理的委托处理代码以及更新事件 { public delegate void InventoryChangeEventHandler (object source, InventoryChangeEventArgs e); public event InventoryChangeEventHandler OnInventoryChangeHandler; //事件监听处理委托,需要添加event关键字 public void UpdateInventory(string sku, int change) { if (0 == change) { return; //No update } InventoryChangeEventArgs e = new InventoryChangeEventArgs(sku, change); if (OnInventoryChangeHandler != null) { OnInventoryChangeHandler(this, e); //初始化托管代码处理器,等待监听处理 } } } class InventoryWatcher //监视器 { public InventoryWatcher(InventoryManager inventoryManager) { this.inventoryManager = inventoryManager; inventoryManager.OnInventoryChangeHandler += new InventoryManager.InventoryChangeEventHandler(OnInventoryHandler); //添加时间监听响应代码 } InventoryManager inventoryManager; void OnInventoryHandler(object source, InventoryChangeEventArgs e) { int change = e.Change; Console.WriteLine("Part '{0}' was {1} by {2} units", e.Sku, change > 0 ? "Increased" : "Decreased", Math.Abs(change)); } } } 测试程序: using System; namespace PublishedAndSubscriber { class TestApp { public static void Main(string[] args) { InventoryManager inventoryManager = new InventoryManager(); InventoryWatcher inventoryWatcher = new InventoryWatcher(inventoryManager); inventoryManager.UpdateInventory("111 016 116", -2); inventoryManager.UpdateInventory("111 005 117", 5); Console.Read(); } } }