📅  最后修改于: 2023-12-03 15:30:16.424000             🧑  作者: Mango
In C#, an event is a message sent by an object to signal the occurrence of an action. The object that raises the event is called the sender, and the object that receives the event is called the listener.
Events are commonly used in graphical user interfaces (GUIs) to respond to user input, such as button clicks or mouse movements. They are also used in server-side applications to notify clients of changes in data or status.
To define an event in C#, you use the event
keyword and specify the delegate type for the event. The delegate type defines the signature of the method(s) that can handle the event. Here's an example:
public class Button {
public event EventHandler Click;
protected virtual void OnClick(EventArgs e) {
Click?.Invoke(this, e);
}
}
In this example, the Button
class defines an event called Click
. The EventHandler
delegate type specifies that the event handlers should have the following signature:
void ClickHandler(object sender, EventArgs e)
The OnClick
method is called when the button is clicked, and it raises the Click
event by invoking the delegate with the this
object (the sender) and an EventArgs
object.
To subscribe to an event in C#, you use the +=
operator to add a method to the event's invocation list, and the -=
operator to remove it. Here's an example:
public class Form {
private Button button;
public Form() {
button = new Button();
button.Click += Button_Click;
}
private void Button_Click(object sender, EventArgs e) {
MessageBox.Show("Button clicked!");
}
}
In this example, the Form
class subscribes to the Click
event of a Button
object. When the button is clicked, the Button_Click
method is called and displays a message box.
Here are some best practices for working with events in C#:
OnClick
method above). If no listeners are subscribed, the event may be null and cause a null reference exception.OnClick
) and the delegate type with "EventHandler" (like EventHandler
or ButtonEventHandler
).Events are a powerful and flexible mechanism for handling application events in C#. By using events, you can write more modular and extensible code that can respond to user input and data changes.