事件的标准用法
namespace EventSample
{
public class CarInfoEventArgs : EventArgs
{
public CarInfoEventArgs(string car)
{
this.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)
{
EventHandler<CarInfoEventArgs> newCarInfo = NewCarInfo;
if (newCarInfo != null)
{
//确保事件的监听函数全都能执行
foreach (EventHandler<CarInfoEventArgs> action in newCarInfo.GetInvocationList())
{
action(this, new CarInfoEventArgs(car));
}
}
}
}
}