Events are a way to allow a class to send a signal indicating that an event of some importance has taken place. Events are most commonly used in the Windows Forms user interface, sending signals indicating that the user has clicked on a button, typed characters, moved the mouse, or any number of other events.
Events can also be used to indicate other important events that don't have anything to do with a user interface, such as indicating that an object's internal state has changed, that data in a list has changed, and so on.
Events are created from delegates using the event keyword. First, you declare the delegate:
delegate void StateChangedDelegate(object state);
Then you declare the event as a member of a class:
public event StateChangedDelegate OnStateChanged;
Finally, the class interested in the event can subscribe to the event in a syntax that should look familiar to you given your recent exposure to multicast delegates:
myClass.OnStateChanged += new StateChangedDelegate(myClass.StateChangedEventHandler);
Now the subscribing class will be notified every time the other class's state changes. By using events, you can then have one piece of code that is
responsible for performing the task, and you could have the user interface
environment subscribe to the progress event. This loose coupling allows you to
reuse your code without any modification in any GUI environment.
No comments:
Post a Comment