首页 > 其他 > 详细

【转载】Subscribe to an Event by Adding an Event Handle

时间:2014-03-13 09:12:05      阅读:397      评论:0      收藏:0      [点我收藏+]

You subscribe to a particular event in C# by defining an event handler-code that will be called whenever the event occurs (is raised). You then attach your event handler to an event on a specific object, using the += operator.

Below is an example where we define an event handler for the Dog.Barked event. Each time that kirby barks, we‘ll record the date and time of the bark in a list.

bubuko.com,布布扣
 1 private static List<DateTime> barkLog = new List<DateTime>();
 2 
 3 static void Main()
 4 {
 5     Dog kirby = new Dog("Kirby", 12);
 6     kirby.Barked += new EventHandler(kirby_Barked);
 7 
 8     kirby.Bark();
 9     Console.ReadLine();
10 
11     kirby.Bark();
12     Console.ReadLine();
13 }
14 
15 // Neither argument is used, for the moment
16 static void kirby_Barked(object sender, EventArgs e)
17 {
18     // Log kirby‘s barks
19     barkLog.Add(DateTime.Now);
20 }
bubuko.com,布布扣

Assuming that the Dog class fires its Barked event whenever we call the Bark method, our handler will get called whenever kirby barks.

【转载】Subscribe to an Event by Adding an Event Handle,布布扣,bubuko.com

【转载】Subscribe to an Event by Adding an Event Handle

原文:http://www.cnblogs.com/yuthreestone/p/3595598.html

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