码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-07-14 14:52:32      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   2014   

运行结果:

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#高级编程》委托、事件的示例代码

标签:des   style   blog   http   color   2014   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!