The notes are from the. NET4.0 Object-Oriented Programming basics chapter-event and event-driven
Tag: Events and multi-channel Delegation
From the object-oriented perspective, an event is a message sent by an object. It is a signal that notifies other objects of the event.
The vectors of events are all objects. The object that inspires an object is called an "event source". The object that responds to this event is called a "responder". The responder must provide an "Event Response (or processing) method ".
Events and multi-channel Delegation
The main feature of an event is one-to-Multiple Association, that is, an event can have multiple responders .. NET event processing mechanism is implemented based on multi-channel delegation.
Example of multi-channel delegate event implementation:
public delegate void MyEventDelegate(int value);
public class EventSource
{
public MyEventDelegate handles;
}
public class EventResponsor
{
public void MyMethod(int i)
{
Console.WriteLine(i);
}
}
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
EventSource p=new EventSource();
EventResponsor responsor1=new EventResponsor();
EventResponsor responsor2=new EventResponsor();
p.handles=System.Delegate.Combine(p.handles,new MyEventDelegate(responsor1.MyMethod)) as MyEventDelegate;
p.handles=System.Delegate.Combine(p.handles,new MyEventDelegate(responsor2.MyMethod)) as MyEventDelegate;
//p.handles+=new MyEventDelegate(responsor1.MyMethod);
//p.handles+=new MyEventDelegate(responsor2.MyMethod);
//or more brief ways
//p.handles+=responsor1.MyMethod;
//p.handles+=responsor2.MyMethod;
p.handles(11);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
Define a delegate first, and then define the EventSource class of the event. the handles of the MyEventDelegate field is its responder list. Define an event responder class EventResponsor, which contains the methods to be used for response.
In the main function, declare an event source object p and two responsor1 and responsor2, and then call the static method of the Delegate class to combine multiple Delegate variables (or directly create a Delegate variable ), finally, manually trigger the event. You can see that there are two responses when you run the program.
In the preceding example, an event is manually triggered, but an actual event cannot be triggered by the outside world. It must be triggered by the event source object. Therefore, a keyword event is introduced. For example:
public delegate void MyEventDelegate(int value);
public class EventSource
{
public event MyEventDelegate handles;
public void FireEvent()
{
if(handles!=null)
handles(11);
}
}
public class EventResponsor
{
public void MyMethod(int i)
{
Console.WriteLine(i);
}
}
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
EventSource p=new EventSource();
EventResponsor responsor1=new EventResponsor();
EventResponsor responsor2=new EventResponsor();
p.handles+=new MyEventDelegate(responsor1.MyMethod);
p.handles+=new MyEventDelegate(responsor2.MyMethod);
//or more brief ways
//p.handles+=responsor1.MyMethod;
//p.handles+=responsor2.MyMethod;
p.FireEvent();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
Change: The handles field of the EventSource class adds the keyword event and the trigger method FireEvent (). The static Delegate method cannot be used when the Delegate variable is combined, the append delegate method + = must be used. The method used to trigger an event also changes to the trigger method FireEvent () provided by the event source class ().
Analysis of. NET event Implementation Mechanism
The author of the book has made a very serious analysis. Let me take a look at the general points.
After adding an event to the Button in the Form, you can see in the Initialize method:
Button btn = new Button();
btn.MouseClick+=new MouseEventHandler(btn_MouseClick);
In the above Code, MouseClick is an event Member of the Button class:
The Button itself defines only two events. The others are inherited from ButtonBase and IButtonControl, which act as handles in the preceding example. Therefore, you can add multiple response functions to the Button.
Summary by the author: the predefined events of all. NET visual form controls are a pair of variables of the "event name + Handler" delegate type. Information related to this event is encapsulated in event parameters of the "event name + Args" type. This event parameter object is derived from EventArgs.
Define your own events:
Steps for customizing events:
1. Create an event-specific delegate that defines the signature of the event response method.
2. Use the event keyword to define an event field for the object
3. Inspire events in appropriate places
Sample Code:
From form: There is a button from the form to add an event to this button
public delegate void ValueChanged(string value);
public event ValueChanged ButtonClicked;
private int counter;
void button1_Click(object sender, EventArgs e)
{
counter++;
if (ButtonClicked != null)
ButtonClicked(counter.ToString());
}
Main form:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
labelInfo = new Label();
labelInfo.Dock = DockStyle.Fill;
labelInfo.Font = new Font("Arail", 14);
labelInfo.BackColor = Color.YellowGreen;
labelInfo.TextAlign = ContentAlignment.MiddleCenter;
this.Controls.Add(labelInfo);
ChildForm c = new ChildForm();
c.ButtonClicked += ShowInfo;
c.Show();
}
private void ShowInfo(string value)
{
labelInfo.Text = value.ToString();
}
Analysis: the main form defines the delegate, event, event, and event trigger mechanisms. The main form adds Custom Event functions to the event container from the form. An event can be viewed as an attribute or field of the Form class, and the value of the method assigned to the event attribute of the main form class during initialization.
Event accessors:
By default, when a class declares an event, the compiler allocates the memory to an event field to store event information. If the class has many unused events, they do not need to occupy the memory.
In this case, you can use the EventHandlerList class provided by. NET Framework to reduce memory usage.
The EventHandlerList class can be viewed as a collection of events to store the list of response methods for various events.
The EventHandlerList object can store multiple response methods for multiple events. Different events are distinguished by Time names. The EventHandlerList object appears only when the event to be responded has a list of method calls.
If you use the EventHandlerList object to save the event response method, you must write a special time accesser for each event:
public delegate void OneDelegate(int value);
public class A
{
private EventHandlerList events=new EventHandlerList();
public event OneDelegate Event1
{
add{events.AddHandler("Event1",value);}
remove{events.RemoveHandler("Event1",value);}
}
}
As you can see, event Event1 is no longer a simple common delegate field with the event keyword, but an event type attribute. add and remove keywords for this event attribute.
Event triggering:
The method for initiating events that define the time accessors is different from the original method.
(EventHandlerList object name [event name] as defines the event Delegate type) (parameter)
Example:
(events["Event1"] as OneDelegate)(100);