事件 (C# 程式設計手冊)Events (C# Programming Guide)

事件可讓 類別 或物件在某些相關的事情發生時,告知其他類別或物件。Events enable a class or object to notify other classes or objects when something of interest occurs. 傳送 (或 「引發」 (raise)) 事件的類別稱為 「發行者」 (publisher),而接收 (或 「處理」 (handle)) 事件的類別則稱為 「訂閱者」 (subscriber)。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 Forms 或 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 Cookbook 第三版:250 個以上 C# 3.0 程式設計人員適用的方案中的委派、事件與 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