首页 > 代码库 > 《C#高级编程》委托、事件的示例代码
《C#高级编程》委托、事件的示例代码
运行结果:
Program.cs
1 using System; 2 3 namespace Wrox.ProCSharp.Delegates 4 { 5 class Program 6 { 7 static void Main() 8 { 9 var dealer = new CarDealer();10 11 var michael = new Consumer("Michael");12 dealer.NewCarInfo += michael.NewCarIsHere;13 14 dealer.NewCar("Mercedes");15 16 var nick = new Consumer("Nick");17 dealer.NewCarInfo += nick.NewCarIsHere;18 19 dealer.NewCar("Ferrari");20 21 dealer.NewCarInfo -= michael.NewCarIsHere;22 23 dealer.NewCar("Toyota");24 25 Console.Read();26 }27 }28 }
CarDealer.cs
1 using System; 2 3 namespace Wrox.ProCSharp.Delegates 4 { 5 public class CarInfoEventArgs : EventArgs 6 { 7 public CarInfoEventArgs(string car) 8 { 9 this.Car = car;10 }11 12 public string Car { get; private set; }13 }14 15 public class CarDealer16 {17 public event EventHandler<CarInfoEventArgs> NewCarInfo;18 19 public void NewCar(string car)20 {21 Console.WriteLine("CarDealer, new car {0}", car);22 if (NewCarInfo != null)23 {24 NewCarInfo(this, new CarInfoEventArgs(car));25 }26 }27 }28 }
Consumer.cs
1 using System; 2 3 namespace Wrox.ProCSharp.Delegates 4 { 5 public class Consumer 6 { 7 private string name; 8 9 public Consumer(string name)10 {11 this.name = name;12 }13 14 public void NewCarIsHere(object sender, CarInfoEventArgs e)15 {16 Console.WriteLine("{0}: car {1} is new", name, e.Car);17 }18 }19 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。