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.
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 moment16 static void kirby_Barked(object sender, EventArgs e)17 {18 // Log kirby's barks19 barkLog.Add(DateTime.Now);20 }
Assuming that the Dog class fires its Barked event whenever we call the Bark method, our handler will get called whenever kirby barks.
原文地址:#370 - Subscribe to an Event by Adding an Event Handle
新闻热点
疑难解答