C# delegate event关系
有几篇文章写的蛮好
点击打开链接http://www.tracefact.net/csharp-programming/delegates-and-events-in-csharp.aspx
点击打开链接http://www.cnblogs.com/lin614/archive/2007/01/30/634576.html
起因:
发现这个event加不加的无所谓嘛,都可以执行的,后来发现有玄机的,参看上面2篇文章。
//public EventHandler<CarInfoArgs> noticeDelegate;
public event EventHandler<CarInfoArgs> noticeDelegate;
class Program { static void Main(string[] args) { Dealer xiaowang = new Dealer("xiaowang"); Consumer lilaoban = new Consumer(); Consumer zhanglaoban = new Consumer(); xiaowang.noticeDelegate +=new EventHandler<CarInfoArgs>( lilaoban.getNotice); xiaowang.noticeDelegate += zhanglaoban.getNotice; xiaowang.notice("qq"); xiaowang.noticeDelegate -= zhanglaoban.getNotice; xiaowang.notice("handrover"); //xiaowang.noticeDelegate = null; Console.ReadLine(); } static void xiaowang_noticeDelegate(object sender, CarInfoArgs e) { throw new NotImplementedException(); } } class CarInfoArgs :EventArgs{ public string carinfo { get; set; } public CarInfoArgs(string car) { this.carinfo = car; } } class Dealer { public string name { get; set; } public Dealer(string name) { this.name = name; } //public EventHandler<CarInfoArgs> noticeDelegate; public event EventHandler<CarInfoArgs> noticeDelegate; public void notice(string car) { if (noticeDelegate != null) { noticeDelegate(this, new CarInfoArgs(car)); } } } class Consumer { public void getNotice(object sender, CarInfoArgs e) { Console.WriteLine("{0} got notice from {1} on car type : {2}",this.ToString(),((Dealer)sender).name,e.carinfo); } }