Guide to the Language


Download 2 Mb.
Pdf ko'rish
bet65/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   61   62   63   64   65   66   67   68   ...   78
Bog'liq
C sharp

CHAPTER 27
Events
Events enable an object to notify other objects when something of interest 
occurs. The object that raises the event is called the publisher and the 
objects that handle the event are called subscribers.
 Publisher
To demonstrate the use of events, a publisher will be created first. This will 
be a class that inherits from ArrayList, but this version will raise an event 
whenever an item is added to the list. Before the event can be created, a 
delegate is needed that will hold the subscribers. This could be any kind 
of delegate, but the standard design pattern is to use a void delegate that 
accepts two parameters. The first parameter specifies the source object of 
the event, and the second parameter is a type that either is or inherits from 
the System.EventArgs class. This parameter usually contains the details of 
the event, but in this example, there is no need to pass any event data and 
so the base EventArgs class will be used as the parameter’s type.
public delegate void
EventHandlerDelegate(object sender, System.EventArgs e);
class Publisher : System.Collections.ArrayList
{
// ...
}


154
 Event Keyword
With the delegate defined, the event can be created in the Publisher 
class using the event keyword followed by the delegate and the name of 
the event. The event keyword creates a special kind of delegate that can 
only be invoked from within the class where it is declared. Its access level 
is public so that other classes are allowed to subscribe to this event. The 
delegate that follows the event keyword is called the event delegate. The 
name of the event is commonly a verb. In this case, the event will be raised 
after the item has been added so the past tense of the verb “Add” is used, 
which is “Added”. If a pre-event was created instead, which is raised before 
the actual event, then the gerund (-ing) form of the verb would be used, in 
this case “Adding”.
public event EventHandlerDelegate Added;
Alternatively, in place of this custom event delegate, the predefined 
System.EventHandler delegate could have been used. This delegate is 
identical to the one defined previously, and it’s used in the .NET class 
libraries for creating events that have no event data.

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   61   62   63   64   65   66   67   68   ...   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling