首页 > 其他 > 详细

《C#高级编程》委托、事件的示例代码

时间:2014-07-14 10:25:10      阅读:316      评论:0      收藏:0      [点我收藏+]

运行结果:

bubuko.com,布布扣

 

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 CarDealer
16     {
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 }

 

《C#高级编程》委托、事件的示例代码,布布扣,bubuko.com

《C#高级编程》委托、事件的示例代码

原文:http://www.cnblogs.com/paullam/p/3841755.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!