Csharp 简明教程
C
Events 是用户操作,如按键、单击、鼠标移动等,或一些事件,如系统生成的通知。应用程序需要在事件发生时对其进行响应。例如,中断。事件用于进程间通信。
Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts. Events are used for inter-process communication.
Using Delegates with Events
事件在一个类中声明和引发,并使用委托与同一类或其他一些类中的事件处理程序关联。类包含用于发布事件的事件。这称为 publisher 类。接受此事件的一些其他类称为 subscriber * class. Events use the *publisher-subscriber 模型。
The events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class. The class containing the event is used to publish the event. This is called the publisher class. Some other class that accepts this event is called the subscriber * class. Events use the *publisher-subscriber model.
publisher 是一个包含事件定义和委托的对象。事件委托关联也在此对象中定义。发布者类对象调用事件并将其通知给其他对象。
A publisher is an object that contains the definition of the event and the delegate. The event-delegate association is also defined in this object. A publisher class object invokes the event and it is notified to other objects.
subscriber 是一个接受事件并提供事件处理程序的对象。发布者类中的委托调用订阅者类的类(事件处理程序)。
A subscriber is an object that accepts the event and provides an event handler. The delegate in the publisher class invokes the method (event handler) of the subscriber class.
Declaring Events
要在类中声明一个事件,首先,你必须为事件声明一个委托类型,如下所示:
To declare an event inside a class, first of all, you must declare a delegate type for the even as:
public delegate string BoilerLogHandler(string str);
然后,使用 event 关键字声明事件 -
then, declare the event using the event keyword −
event BoilerLogHandler BoilerEventLog;
前面的代码定义了一个名为 BoilerLogHandler 的委托和一个名为 BoilerEventLog 的事件,该事件在引发时调用委托。
The preceding code defines a delegate named BoilerLogHandler and an event named BoilerEventLog, which invokes the delegate when it is raised.
Example
using System;
namespace SampleApp {
public delegate string MyDel(string str);
class EventProgram {
event MyDel MyEvent;
public EventProgram() {
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username) {
return "Welcome " + username;
}
static void Main(string[] args) {
EventProgram obj1 = new EventProgram();
string result = obj1.MyEvent("Tutorials Point");
Console.WriteLine(result);
}
}
}
编译并执行上述代码后,将产生以下结果 −
When the above code is compiled and executed, it produces the following result −
Welcome Tutorials Point