下载app免费领取会员
,net 4.5 为弱事件提供了新的实现。泛型类 WeakEventManager<TEventSource, TEventArgs>,它派生自基类WeakEventManager,
大大的简化了弱事件的处理
static void Main(string[] args)
{
CarDealer dealer = new CarDealer();
Consumer micheal = new Consumer("Micheal");
//是用下面两种订阅事件效果不一样
WeakEventManager<CarDealer, CarInfoEventArgs>.AddHandler(dealer, "NewCarInfo", micheal.NewCarIsHere);
//dealer.NewCarInfo += micheal.NewCarIsHere;
dealer.NewCar("Ferrari");
micheal = null;
GC.Collect();
dealer.NewCar("Ferrari");
Console.ReadLine();
}
}
public class CarInfoEventArgs:EventArgs
{
public CarInfoEventArgs(string car)
{
Car = car;
}
public string Car { get; private set; }
}
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)
{
if(NewCarInfo!=null)
{
NewCarInfo(this, new CarInfoEventArgs(car));
}
}
}
public class Consumer
{
private string _name = string.Empty;
public Consumer(string name)
{
_name = name;
}
public void NewCarIsHere(object sender,CarInfoEventArgs e)
{
Console.WriteLine("{0}:Car {1} is new", _name, e.Car);
}
}
本文版权归腿腿教学网及原创作者所有,未经授权,谢绝转载。