C event accessor detail
- 2020-06-03 08:08:06
- OfStack
We can control the behavior of event operators += and -= by defining event accessors for events
The & # 8226; There are two accessors :add and remove
The & # 8226; An accessor that declares an event looks similar to declaring a property
The following example demonstrates a declaration with accessors. Both accessors have implicit value parameters called value, which take references to instances or static methods
public event EventHandler Elapsed
{
add
{
//... perform += The code for the operator
}
remove
{
//... perform -= The code for the operator
}
}
Once the event accessor is declared, the event does not contain any embedded delegate objects. We must implement our own mechanism to store and remove the method of the event
Event accessors are represented as void methods, which means that return statements that return values cannot be used
Complete example:
// The statement 1 a delegate
delegate void EventHandler();
class MyClass
{
// The statement 1 A member variable to hold an event handle that is called when the event is fired delegate )
private EventHandler m_Handler = null;
// Trigger events
public void FireAEvent()
{
if (m_Handler != null)
{
m_Handler();
}
}
// The statement event
public event EventHandler AEvent
{
// Add accessor
add
{
// Pay attention to , The accessor actually contains 1 called value Implied parameter of
// The value of this parameter is the client call += " delegate
Console.WriteLine("AEvent add Is called ,value the HashCode for :" + value.GetHashCode());
if (value != null)
{
// Set up the m_Handler Domain saves new handler
m_Handler = value;
}
}
// Delete accessor
remove
{
Console.WriteLine("AEvent remove Is called ,value the HashCode for :" + value.GetHashCode());
if (value == m_Handler)
{
// Set up the m_Handler for null, The event will no longer be triggered
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 the delegate to the event
obj.AEvent += MyHandler;
// Trigger events
obj.FireAEvent();
// Revoke the delegate from the event
obj.AEvent -= MyHandler;
// Refiring event
obj.FireAEvent();
Console.ReadKey();
}
// Event handler
static void MyEventHandler()
{
Console.WriteLine("This is a Event!");
}
// Event handler
static void MyEventHandle2()
{
Console.WriteLine("This is a Event2!");
}
}