CarDealer类发布事件,Consumer类(实现IWeakEventListener接口)订阅事件
实现代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; namespace ConsoleDelegate { class Program { static void Main(string[] args) { CarDealer dealer = new CarDealer("Obama"); Consumer Jack = new Consumer("Jack"); WeakCarInfoEventManager.AddListener(dealer, Jack); dealer.NewCar("BMW"); Consumer Bidden = new Consumer("Bidden"); WeakCarInfoEventManager.AddListener(dealer, Bidden); dealer.NewCar("EAGLE"); } } public class CarInfoEventArgs : EventArgs { public CarInfoEventArgs(string name) { this.Car = name; } public string Car { get; private set; } } public class CarDealer { private string name; public CarDealer(string name) { this.name = name; } public event EventHandler<CarInfoEventArgs> NewCarInfo; public void NewCar(string car) { Console.WriteLine("{0}, New Car: {1}", name, car); NewCarInfo(this, new CarInfoEventArgs(car)); } } public class Consumer : IWeakEventListener { private string name; public Consumer(string name) { this.name = name; } private void NewCarIsHere(object sender, CarInfoEventArgs e) { Console.WriteLine("{0}, new car :{0} is here............", name, e.Car); } bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object source, EventArgs e) { NewCarIsHere(source, e as CarInfoEventArgs); return true; } } public class WeakCarInfoEventManager : WeakEventManager { public static void AddListener(object source,IWeakEventListener e) { CurrentManager.ProtectedAddListener(source, e); } public static void RemoveListener(object source, IWeakEventListener e) { CurrentManager.ProtectedRemoveListener(source, e); } public static WeakCarInfoEventManager CurrentManager { get { WeakCarInfoEventManager manager = GetCurrentManager(typeof(WeakCarInfoEventManager)) as WeakCarInfoEventManager; if(manager ==null) { manager = new WeakCarInfoEventManager(); SetCurrentManager(typeof(WeakCarInfoEventManager), manager); } return manager; } } protected override void StartListening(object source) { (source as CarDealer).NewCarInfo += CarDealer_NewCarInfo; } public void CarDealer_NewCarInfo(object sender, CarInfoEventArgs e) { DeliverEvent(sender, e); } protected override void StopListening(object source) { (source as CarDealer).NewCarInfo += CarDealer_NewCarInfo; } } }
转载:http://blog.csdn.net/foreverling/article/details/38312927