事件是类在发生其关注的事情时用来提供通知的一种方式。例如,封装用户界面控件的类可以定义一个在用户单击该控件时发生的事件。控件类不关心单击按钮时发生了什么,但它需要告知派生类单击事件已发生。然后,派生类可选择如何响应。
事件使用委托来为触发时将调用的方法提供类型安全的封装。委托可以封装命名方法和匿名方法。
在下面的示例中,类 TestButton
包含事件 OnClick。派生自 TestButton
的类可以选择响应 OnClick 事件,并且定义了处理事件要调用的方法。可以以委托和匿名方法的形式指定多个处理程序。
C# | ![]() |
---|---|
// Declare the handler delegate for the event public delegate void ButtonEventHandler(); class TestButton { // OnClick is an event, implemented by a delegate ButtonEventHandler. public event ButtonEventHandler OnClick; // A method that triggers the event: public void Click() { OnClick(); } } |
C# | ![]() |
---|---|
// Create an instance of the TestButton class. TestButton mb = new TestButton(); // Specify the method that will be triggered by the OnClick event. mb.OnClick += new ButtonEventHandler(TestHandler); // Specify an additional anonymous method. mb.OnClick += delegate { System.Console.WriteLine("Hello, World!"); }; // Trigger the event mb.Click(); |
事件概述
事件具有以下特点:
-
事件是类用来通知对象需要执行某种操作的方式。
-
尽管事件在其他时候(如信号状态更改)也很有用,事件通常还是用在图形用户界面中。
-
事件通常使用委托事件处理程序进行声明。
-
事件可以调用匿名方法来替代委托。有关更多信息,请参见匿名方法。
相关章节
有关更多信息,请参见:
C# 语言规范
有关更多信息,请参见 C# 语言规范中的以下各章节:
-
1.6.6.4 事件
-
10.2.7.2 事件的保留成员名称
-
10.7 事件
-
13.2.3 接口事件