C # delegation and events,
I have always used it only, but I don't quite understand it. I read this article today and I have received some goods. I will repost it here ····· Original article address:C # Delegate and Event _ 1544Author:Feng Yiliu 3.10.2 declares that the incident has the following characteristics:
Q events generally use the delegate event handler's inbound and termination declarations.
Q events always notify objects of messages and instigate a method that requires certain operations.
Q. The publisher must be certain when an event is triggered, and the subscriber must perform any operation to respond to the event.
Q an event can have fewer subscribers. A subscriber can handle a small number of events from a few senders.
Q events with subscribers are never called.
Q events are usually used to notify users of operations, such as button doubles or double menu selections on the graphic user interface.
Q if an event has multiple subscribers, multiple event handlers can be used simultaneously when an event is triggered, or multiple events can be processed asynchronously.
The event and method are the same. Generally, the event and method are used together. The event and the delegate have the same signature, but the event signature is defined by the delegate type. The sample method code is as follows.
Public delegate void MyDel (object sender, EventArgs e); // declare a delegate
Public class Event // write the Event class
{
Public event MyDel EventTest; // declare an event
Public void EventTestMethod () // compile the event Method
{
Console. WriteLine ("event used"); // output string
}
}
In the above Code, a delegate is declared. After the delegate is declared, an Event is highlighted in the Event class, and the Event is bound to MyDel. In the event signature, the first parameter is the object that invokes the event stream. The second parameter is a class that transmits data related to the event. In C #, standard code writing can make the code more readable and BB cream.
3.10.3 if an event is to be triggered, the class can call the delegate and send all parameters with closed events. As mentioned in the previous chapter, events are usually used together with delegates and can be used to send suspicious tasks to delegates to trigger events. If the event has any handler, the event is empty. Therefore, before the event is triggered, you must first make sure that the event is not empty; otherwise, NullReferenceException is thrown, the code for triggering an event is as follows.
Public delegate void MyDel (object sender, EventArgs e); // create
Public class Event // write the Event class
{
Public event MyDel EventTest; // declare an event
Public void EventTestMethod () // declare the method for executing an event
{
MyDel OnLoad = EventTest; // Method for declaring an event
If (OnLoad! = Null) // determines whether the event can be empty.
{
OnLoad (this, EventArgs (); // use the delegate if it is not empty
}
}
}
Each event can be assigned multiple programs to take over the event. In this way, the event actively calls each absorber. When there are multiple receivers, only one event needs to be called to trigger the event.
3.10.4 subscribe to an event as a method. To accept an event class, you can create a method to receive the event, the class event that receives the event is added with the delegate of the method. This is called "subscription event". It can be said that the whole process of RSS subscription on the internet is similar to that on the Internet. It is worth noting that the receiver must have the same signature method for the event itself, and then when the method capability is used to echo the event, the sample code is as follows.
Public class EventReceiver // creates a pipe adapter
{
Public void EventTestReceiver (object sender, EventArgs e) // the signature of the method must be the same
{
Console. WriteLine ("from" + sender. ToString () + ""); // execution method body
}
}
Each event can be assigned multiple programs to receive the event, that is, there can be multiple receivers. Multiple receivers are called by the stream in sequence. If an absorption is very present, an accepted receiver will receive the event. If you want to subscribe to an event, the receiver must create a delegate of the same type as the event and use the event to process the delegate, this is why events are usually used together with delegates. The sample code is as follows.
Public void EventTestSubscribe (Event eve)
{
MyDel del = new MyDel (EventTestReceiver); // declare the delegate
Eve. EventTest + = del; // Add events
}
In the above Code, you subscribe to a task through the "+ =" operator. Similarly, you can use the "-=" operator to unsubscribe to a task. The sample code is as follows.
Public void EventTestSubscribe (Event eve)
{
MyDel del = new MyDel (EventTestReceiver); // please
Eve. EventTest-= del; // undo the event
}
3.10.5 delegation and events the above section left the teaching of delegation and events. It is difficult to learn about delegation and events for beginners. However, after further study of delegation and events, will invent the commission and the incident is very simple. Inspired by ASP. NET, many controls use delegation and events. For example, when a button control is used in doubles, the button will send a message to "trigger a button event" and then send it to a considerable absorber, the Access Manager accepts the sent information and causes a considerable number of operations. After understanding the basics of delegation and events, the following code illustrates how to use delegation and events step by step.
In order to achieve the function of broadcasting the horn (similar to QQ's system-centered questions), there is no user-centered conversation window in the program, but also the system-based sending window. The system can send system information to the user's conversation window, which is in use. It not only needs to broadcast the user's information, but also the system can play system information. To achieve that, you must first create a delegate. The sample code is as follows.
Public delegate void BetaDel string str); // creates a delegate
After a delegate is created, the write method is required. The sample code is as follows.
Public delegate void BetaDel (string str );
Public static void Output (string str) // method of sending and receiving questions
{
Console. WriteLine ("the user sends you a message"); // output the user notification information
}
Public static void SystemOutput (string str) // system message sending Method
{
Console. WriteLine ("a message is sent to you by the system"); // The user notification is output.
}
Public static void OutputChoose (string str, BetaDel del) // use delegate deterioration
{
Del (str );
}
Note: In the above Code, del is a delegation deterioration. del (str) is executed in the delegate method table according to the method signature. In the above Code, the methods with the same del (string str) signature are Output and SystemOutput, and their signatures are similar.
In the main function, you can use the function by Delegate. The sample code is as follows.
Static void Main (string [] args)
{
OutputChoose ("", Output); // method of use
Console. ReadKey ();
}
The OutputChoose method is used in the above Code. It is worth noting that in the OutputChoose method, the 400 phone number, one of the parameters is the method name. Through delegation, you can use the method name as a parameter for input transmission, and execute a considerable number of methods. It is worth noting that in the above Code, all delegate and other methods are declared in a class, because it can be easily understood, but it does not have the characteristics of back-to-back, the feature of the Back-to-Surface object is encapsulation, which enables code to be constructive, so events can be used. Create a class named OutputChoose. The sample code is as follows.
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text; // use the System namespace
Namespace beta
{
Class OutputChoose
{
Public string message = "you have a new message owed, please check"; // declare the message string owed
Public delegate void BetaDel (string str); // predefined delegate registration event
Public event BetaDel MyEvent; // declare an event
Public void OnLoad () // write the OnLoad method to register an event
{
If (MyEvent! = Null)
{
MyEvent (message); // call the methods of all registered objects when an event exists.
}
}
}
}
The above Code encapsulates the methods in the previous code as the delegate. Add a user news class named UserMessage. The sample code is as follows.
Using System. Linq;
Using System. Text; // use the whitelist to handle the actual space.
Namespace beta // declare the future order of real space
{
Class UserMessage
{
Public void Output (string str) // Output Method
{
Console. WriteLine ("the user sends you a news:" + str); // brief output
}
}
}
Add a system news class named SystemMessage. The sample code is as follows.
Using System. Linq;
Using System. Text; // use a whitelist to process namespaces.
Namespace beta // declare the future sequential namespace
{
Class SystemMessage
{
Public void SystemOutput (string str) // System acquisition and Output Method
{
Console. WriteLine ("system sends you an audio:" + str); // The audio sent by the explicit system
}
}
}
The main function can trigger events. The sample code is as follows.
Static void Main (string [] args)
{
OutputChoose opc = new OutputChoose (); // declare the object
SystemMessage msg = new SystemMessage ();
Opc. MyEvent + = msg. SystemOutput; // Registration Method
Opc. OnLoad (); // start to actively call all registration methods
Console. ReadKey ();
}
In the above Code, OnLoad () triggers the previously registered event and executes the event, as shown in Figure 3-8.
Figure 3-8 Combined Use Cases of delegation and events
Running results show that when an object is created, the object can register the Declaration event. Because the object does not have the detailed and hidden methods of the event, the method is increased in the event, it is similar to adding a method to the class. In the class encoding, an OnLoad method is defined to call all methods for registering objects.