【转载】#370 - Subscribe to an Event by Adding an Event Handle

本文介绍如何在C#中定义并订阅一个特定对象的事件。通过实例展示了当Dog对象发出Barked事件时,如何记录每次事件触发的时间。

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 moment
16 static void kirby_Barked(object sender, EventArgs e)
17 {
18     // Log kirby's barks
19     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

转载于:https://www.cnblogs.com/yuthreestone/p/3595598.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值