WeakEvent的使用

2017-12-26  本文已影响0人  若水生花啊啊啊
class Program
    {
        static void Main(string[] args)
        {
            var dealer = new CarDealer();

            var michael = new Consumer("Michael");
            WeakEventManager<CarDealer, CarInfoEventArgs>.AddHandler(dealer, "NewCarInfo", michael.NewCarIsHere);

            dealer.NewCar("Mercedes");
            Console.WriteLine("-----------------------------------------------------------------");
            var sebastian = new Consumer("Sebastian");
            WeakEventManager<CarDealer, CarInfoEventArgs>.AddHandler(dealer, "NewCarInfo", sebastian.NewCarIsHere);
            dealer.NewCar("Ferrari");
            Console.WriteLine("-----------------------------------------------------------------");
            WeakEventManager<CarDealer, CarInfoEventArgs>.RemoveHandler(dealer, "NewCarInfo", michael.NewCarIsHere);
            dealer.NewCar("Red Bull Racing");

            Console.ReadKey();
        }
    }

    public class CarInfoEventArgs : EventArgs
    {
        public CarInfoEventArgs(string car)
        {
            this.Car = car;
        }
        public string Car { get; private set; }
    }

    public class Consumer
    {
        private string name;

        public Consumer(string name)
        {
            this.name = name;
        }

        public void NewCarIsHere(object sender, CarInfoEventArgs e)
        {
            Console.WriteLine("{0}: car {1} is new", name, e.Car);
        }
    }

    public class CarDealer
    {
        public event EventHandler<CarInfoEventArgs> NewCarInfo;

        public void NewCar(string car)
        {
            Console.WriteLine("CarDealer,new car {0}", car);

            RaiseNewCarInfo(car);
        }

        protected virtual void RaiseNewCarInfo(string car)
        {
            EventHandler<CarInfoEventArgs> newCarInfo = NewCarInfo;
            if (newCarInfo != null)
            {
                newCarInfo(this, new CarInfoEventArgs(car));
            }
        }
    }

在使用WeakEvent的过程中除了要加入Windows命名空间的引用外,还需要注意AddHandler和RemoveHandler的第二参数虽然是个字符串,但是它表明的时源事件的代理,AddHandler或者RemoveHandler会搜索它来注册事件或者注销事件,所以它是特定的源事件的代理的字符表示。

上一篇下一篇

猜你喜欢

热点阅读