委托、 Lambda表达式和事件——事件

 1 /*
 2  * 由SharpDevelop创建。
 3  * 用户: David Huang
 4  * 日期: 2015/7/31
 5  * 时间: 14:21
 6  */
 7 using System;
 8 
 9 namespace 事件
10 {
11     public class GameInfoEventArgs:EventArgs
12     {
13         public string Game{get;set;}
14         
15         public GameInfoEventArgs(string game)
16         {
17             this.Game = game;
18         }
19     }
20     
21     public class TV
22     {
23         public event EventHandler<GameInfoEventArgs> NewGame;
24         
25         public void GameStart(string game)
26         {
27             Console.WriteLine("{0}的比赛开始了。",game);
28             
29             if (NewGame!=null) {
30                 NewGame(this,new GameInfoEventArgs(game));
31             }
32         }
33         
34     }
35     
36     public class Person
37     {
38         public string Name{get;set;}
39         
40         public Person(string name)
41         {
42             this.Name=name;
43         }
44         
45         public void WatchGame(object sender,GameInfoEventArgs e)
46         {
47             Console.WriteLine("{0}开始看{1}的比赛。",Name,e.Game);
48         }
49     }
50     
51     class Program
52     {
53         public static void Main(string[] args)
54         {
55 
56             TV tv=new TV();
57             
58             Person me=new Person("");
59             tv.NewGame+=me.WatchGame;
60             
61             Person tom=new Person("tom");
62             tv.NewGame+=tom.WatchGame;
63             
64             tv.GameStart("曼联");
65             
66             Console.Write("Press any key to continue . . . ");
67             Console.ReadKey(true);
68         }
69     }
70 }

 

posted @ 2015-07-31 15:28  David Huang  阅读(280)  评论(0编辑  收藏  举报