事件(C# 编程指南)Events (C# Programming Guide)

或对象可以通过事件向其他类或对象通知发生的相关事情。Events enable a class or object to notify other classes or objects when something of interest occurs. 发送(或引发 )事件的类称为“发布者” ,接收(或处理 )事件的类称为“订阅者” 。The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.

在典型的 C# Windows 窗体或 Web 应用程序中,可订阅由按钮和列表框等控件引发的事件。In a typical C# Windows Forms or Web application, you subscribe to events raised by controls such as buttons and list boxes. 可以使用 Visual C# 集成开发环境 (IDE) 来浏览控件发布的事件,并选择想要处理的事件。You can use the Visual C# integrated development environment (IDE) to browse the events that a control publishes and select the ones that you want to handle. 借助 IDE,可轻松自动添加空白事件处理程序方法以及要订阅该事件的代码。The IDE provides an easy way to automatically add an empty event handler method and the code to subscribe to the event. 有关更多信息,请参阅如何:订阅和取消订阅事件For more information, see How to: Subscribe to and Unsubscribe from Events.

事件概述Events Overview

事件具有以下属性:Events have the following properties:

  • 发行者确定何时引发事件;订户确定对事件作出何种响应。The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event.

  • 一个事件可以有多个订户。An event can have multiple subscribers. 订户可以处理来自多个发行者的多个事件。A subscriber can handle multiple events from multiple publishers.

  • 没有订户的事件永远也不会引发。Events that have no subscribers are never raised.

  • 事件通常用于表示用户操作,例如单击按钮或图形用户界面中的菜单选项。Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces.

  • 当事件具有多个订户时,引发该事件时会同步调用事件处理程序。When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised. 若要异步调用事件,请参阅 Calling Synchronous Methods AsynchronouslyTo invoke events asynchronously, see Calling Synchronous Methods Asynchronously.

  • 在 .NET Framework 类库中,事件基于 EventHandler 委托和 EventArgs 基类。In the .NET Framework class library, events are based on the EventHandler delegate and the EventArgs base class.

有关详细信息,请参阅:For more information, see:

C# 语言规范C# Language Specification

有关详细信息,请参阅 C# 语言规范中的事件For more information, see Events in the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

[C# 3.0 手册(第三版):面向 C# 3.0 程序员的超过 250 个解决方案中的委托、事件和 Lambda 表达式Delegates, Events, and Lambda Expressions in C# 3.0 Cookbook, Third Edition: More than 250 solutions for C# 3.0 programmers

[学习 C# 3.0:掌握 C# 3.0 基础知识中的委托和事件Delegates and Events in Learning C# 3.0: Master the fundamentals of C# 3.0

请参阅See also