事件基于委托,为委托提供了一种发布/订阅机制。
public class CarInfoEventArgs:EventArgs
{
public CarInfoEventArgs(string car)
{
this.Car = car;
}
public string Car { get; set; }
}
public class CarDealer
{
public event EventHandler<CarInfoEventArgs> NewCarInfo;
public void NewCar(string car)
{
Console.WriteLine("CarDealer, new car {0}",car);
RaiseNewCarInfo(car);
}
public virtual void RaiseNewCarInfo(string car)
{
EventHandler<CarInfoEventArgs> newCarInfo = NewCarInfo;
if(newCarInfo!=null)
{
newCarInfo(this,new CarInfoEventArgs(car));
}
}
}
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 );
}
}
static void Main()
{
var dealer = new CarDealer();
var michael = new Consumer("michael");
dealer.NewCarInfo += michael.NewCarIsHere;
dealer.NewCar("Ferrari");
var zhangsan = new Consumer("zhangsan");
dealer.NewCarInfo += zhangsan.NewCarIsHere;
dealer.NewCar("lisi");
dealer.NewCarInfo -= michael.NewCarIsHere;
dealer.NewCar("Red Bull Racing");
Console.ReadKey();
}