Guide to the Language


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

 Event Caller
To invoke the event, an event caller can be created. The naming 
convention for this method is to precede the event’s name with the word 
On, which in this case becomes OnAdded. The method has the protected 
access level to prevent it from being called from an unrelated class, and it is 
marked as virtual to allow deriving classes to override it. It takes the event 
arguments as its one parameter, which in this case is of the EventArgs type. 
The method will raise the event only if it is not null, meaning only when 
Chapter 27 events


155
the event has any registered subscribers. To raise the event, the instance 
reference this is passed as the sender, and the EventArgs object is the 
object that was passed to the method.
protected virtual void OnAdded(System.EventArgs e)
{
if (Added != null) Added(this, e);
}
 Raising Events
Now that the class has an event and a method for calling it, the final step 
is to override the ArrayList’s Add method to make it raise the event. In 
this overridden version of the method, the base class’s Add method is first 
called, and the result is stored. The event is then raised with the OnAdded 
method by passing to it the Empty field in the System.EventArgs class, 
which represents an event with no data. Finally, the result is returned to 
the caller.
public override int Add(object value)
{
int i = base.Add(value);
OnAdded(System.EventArgs.Empty);
return i;
}
The complete Publisher class now has the following appearance.
class Publisher : System.Collections.ArrayList
{
public delegate void
EventHandlerDelegate(object sender, System.EventArgs e);
Chapter 27 events


156
public event EventHandlerDelegate Added;
protected virtual void OnAdded(System.EventArgs e)
{
if (Added != null) Added(this, e);
}
public override int Add(object value)
{
int i = base.Add(value);
OnAdded(System.EventArgs.Empty);
return i;
}
}
 Subscriber
To use the Publisher class, another class will be created that will subscribe 
to the event.
class Subscriber
{
//...
}
This class contains an event handler, which is a method that has the 
same signature as the event delegate and is used to handle an event. The 
name of the handler is commonly the same as the name of the event 
followed by the EventHandler suffix.
Chapter 27 events


157
class Subscriber
{
public void AddedEventHandler(object sender, System.EventArgs e)
{
System.Console.WriteLine("AddEvent occurred");
}
}

Download 2 Mb.

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




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