We can control the behavior of the event operator + =, by defining an event accessor for an event
There are two accessors: Add and remove
The accessor that declares the event looks almost as if it were declaring an attribute
The following example shows a declaration with an accessor. Two accessors have implicit value parameters called value that accept references to instances or static methods
Public event EventHandler Elapsed
{
Add
{
//... Code executing the + = operator
}
Remove
{
//... Code that executes the-= operator
}
}
When an event accessor is declared, the event does not contain any inline delegate objects. We have to implement our own mechanism for storing and removing events
The event accessor behaves as a void method, i.e. a return statement that returns a value cannot be used
Complete Example:
Declare a delegate
delegate void EventHandler ();
Class MyClass
{
Declare a member variable to hold the event handle (delegate that is invoked when the event is fired)
Private EventHandler M_handler = null;
Firing events
public void Fireaevent ()
{
if (M_handler!= null)
{
M_handler ();
}
}
declaring events
Public event EventHandler Aevent
{
Add accessor
Add
{
Notice that the accessor actually contains an implied parameter named value
The value of this parameter is called by the client program + = Newsletters Hand over delegate
Console.WriteLine ("Aevent Add" is invoked, the value of Hashcode is: "+ value. GetHashCode ());
if (value!= null)
{
Set the M_handler domain to save the new handler
M_handler = value;
}
}
Delete accessor
Remove
{
Console.WriteLine ("Aevent remove is called, Value hashcode is:" + value. GetHashCode ());
if (value = = M_handler)
{
Set M_handler to NULL, the event will no longer be fired
M_handler = null;
}
}
}
}
Class Program
{
static void Main (string[] args)
{
MyClass obj = new MyClass ();
Create a delegate
EventHandler MyHandler = new EventHandler (MyEventHandler);
MyHandler + = MyEventHandle2;
Register a delegate to an event
Obj. Aevent + = MyHandler;
Firing events
Obj. Fireaevent ();
To revoke a delegate from an event
Obj. Aevent-= MyHandler;
Fire events again
Obj. Fireaevent ();
Console.readkey ();
}
Event handlers
static void MyEventHandler ()
{
Console.WriteLine ("This is a event!");
}
Event handlers
static void MyEventHandle2 ()
{
Console.WriteLine ("This is a event2!");
}
}