下載app免費(fèi)領(lǐng)取會(huì)員
,net 4.5 為弱事件提供了新的實(shí)現(xiàn)。泛型類 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);
}
}
本文版權(quán)歸腿腿教學(xué)網(wǎng)及原創(chuàng)作者所有,未經(jīng)授權(quán),謝絕轉(zhuǎn)載。
下一篇:二次開發(fā)教程:Revit開發(fā)之管道的布管系統(tǒng)配置
推薦專題