9. Delegate, event, Lambda, and delegate event lambda
There must be a problem with delegation.
The first question is what is delegated? Look at the description in. net: On the. net platform, the delegate type is used to define and callback in the corresponding application. (Callback? A technique used to process two physical bidirectional communication in the memory .) The second question is: Delegate and C ++ (actually originated from C) function pointers? It must be said that the difference, although the delegate and function pointer both point to the method to be called in the future. However, delegation has two main advantages over function pointers: 1. Delegation is an object (we know that delegation and class are at one level ). 2. Delegation is built with support for multi-channel broadcast and Asynchronous Method calls.
About events.
Question: What are events used? Events are delegated services, which make it easier and more efficient for us to process Delegate types.
About Lambda.
Q: What does this thing do? Lambda uses the operator => to make it easier for us to call the delegate. OK, it seems that this is closely related to delegation. Knowing what a delegation is, you can understand what an event and Lambda are. 1. The callback function before the. net delegate type, function pointer in C, that is, a block pointing to memory address. We don't know much about the type, such as what type, what return value, and mom egg. After being delegated, I felt that the previous callback was not secure, so I became a type-safe object, pointing to the methods that will be called in the Program (which can be multiple. Willfulness !) 1. What can a delegate contain? What are the benefits of these things? The name of the function method it calls; the method parameter (optional); the return value of the method (optional ). With these features, I can dynamically call the pointing method at runtime. As a result, this delegate will automatically have the ability to synchronize or access a method, so it does not need the Thread to call the auxiliary method, which simplifies programming. 2. What did the Commission do and how did it do it? Definition: public delegate int BinaryOp (int x, int y); return an integer by pointing to two integers in the operation. During compilation, the Delegate will become something that has three common methods: Invoke, BeginInvoke, and EndInvoke. The first method is called synchronously, and the last two are called asynchronously. Asynchronous calls are generally used to call time-consuming methods. (We often use it when writing interfaces, so that it can be called asynchronously without affecting interface movement and other operations .) In the memory, their representation is often as follows (the underlined red line can be written as the return type and parameter type (regardless of the number): It can be seen from the pseudo code above, the delegate is actually something at a level with the class. It also has a base class, two base classes: System. multicastDelegate and System. delegate base class. Simple delegated instance (addition of two numbers): How can this problem be solved? The delegate is at the underlying layer. In fact, the invoke method generated by the compiler is called on the MulticastDelegate derived class. Delegate type security: if you try to pass an unmatched method into the delegate, you will receive a compilation error (for example, the delegate you passed in a parameter method .) 3. How do I send an object notification to the delegate? Define a Car class. Its public members are as follows: Define the delegate to determine whether the maximum value will be exceeded during acceleration and crash: The following is the acceleration method, when the speed is different, output some different information: in the Main method of Program, each time the speed is 20, and the output after each acceleration is recorded: The call result is as follows, you can summarize the steps for delegated notification: Define the delegate type for sending the notification to the caller. Declare the member variables of each delegate type. Create an auxiliary function in the tears to enable the caller to specify the method for saving the delegate member variable. Modify the method to call the call list in the delegate when appropriate. What is multi-channel broadcasting? This means that a delegate object can maintain a list of callable methods, not just a separate method. How? The + = and-= operators are involved. The preceding delegate call method writes another one: Modify the method in Car: Call code: Result: Similarly, if you want to remove the method, use the-= Operator. This is equivalent to the unsubscribe function. 4. method group conversion syntax C # provides the method group conversion syntax to facilitate delegate operations. This allows us to directly provide the name of a method when calling a delegate as a parameter, instead of creating a delegate object. For example, the above process of creating a delegate object can all be saved and become the following code: c1.RegistWithCarEngine (OnCarEngineEvent2); 5. for example, if we derive a NewCar class and create a delegate type, we can point to the method that returns the class. Because the delegate is a security type, we cannot use the delegate that returns the Car. We must define a new delegate. The delegate covariant allows us to create a delegate that can point to the return class and the relevant inheritance system. We can perform a forced conversion to obtain the above delegate result that returns the Car. CarDelegate car = new carDelegate (new NewCar (xxx); NewCar newCar = (NewCar) car ;. 6. Generic delegate C # allows us to define generic Delegate types. For example, suppose we want to define a delegate type to call any method that returns void and accepts a single parameter. If this parameter may be different, we can build it through the type parameter. Generic delegation provides a more flexible way to specify a type-safe method for calling. Previously, we generally used System. object parameters to achieve a similar purpose: public delegate void MyDelegate (object arg); however, we will lose the type security and possibly cause packing loss. Ii. problems encountered when C # events use delegation. (Damage encapsulation) if we do not define the delegate as private, the caller can directly access the delegate object. In this way, the caller can also assign a variable value to the new delegate object. Ooops! This problem occurs. The previous method is equivalent to deleting, And the caller can directly call the call list of the delegate. In a word, public members break the encapsulation, which will not only make the code difficult to maintain and debug, but also lead to application security risks. 1. Is the event dry? What should I do? If the problem is mentioned above, the event will come out and you will know that the event is doing this. (Packaging Commission, so that it does not damage encapsulation ). How can this problem be achieved? When the compiler processes the event keyword, it automatically provides the registration and logout methods and any necessary delegate type member variables (which seems to simplify delegation ), and these delegate member variables are always private, so it is impossible to access them (Oh, secure) from the object that triggers the event ). Event usage: The following is the modified acceleration method: 2. How does the event encapsulate delegation? (In addition to setting the delegate to private by default, there are also the following encapsulation) add _ and remove _ prefixes. For example, the above AboutToBlow event is encapsulated in the pencil Code as follows: it can be seen that the event only saves the input event. The following describes how to listen to the incoming event on the caller side. C # events also simplify the operations for registering caller event handlers. Currently, you do not need to specify custom helper methods. callers only need to use the + = and-= operators (the operator will trigger the correct add_xxx () method or remove_xxx () method in the background ). Use the C # event registration syntax to modify the Main method: Of course, you can also use the method group conversion syntax. The statement is no longer stated. 3. create custom event parameters. What is the event model recommended by Microsoft? When you view an event of a type in the base class library, you will find that the first parameter of the underlying delegate is a System. Object, and the second parameter is a subtype derived from System. EventArgs. System. EventArgs base class, indicating an event that does not send any custom information: Therefore, if we want to pass custom data, we need to create a class derived from EventArgs. We can modify the delegate and add a CarEventArgs parameter to transfer data. (Events remain unchanged .) Public delegate void CarEngineHandler (object sender, CarEventArgs args); // defines the delegate call method: if (Exploded! = Null) {Exploded (this, new CarEventArgs ("Sorry, this car is dead... ");} How the receiver wants to interact with the object that sends the event, we can actually forcibly convert the System. object. In this way, the event can be passed to any public member in the object. III. C # How does the anonymous method work? This is really a wave of events. First, the delegation solved the insecure function pointer, but later it was too troublesome and there was another event. As a result, the event seems to be too long-winded. Well, the anonymous method was launched: the above registered event handler was changed to: c1.AboutToBlow + = delegate (object sender, CarEventArgs e) {Console. writeLine ("Eek! Going to fast! ") ;}; It seems that the processing and registration Declaration are included. Note: The last braces in the anonymous method must end with good points. Otherwise, a compilation error will occur. The following is the pseudocode of the syntax of the anonymous method: the anonymous method is very interesting, and it allows us to access the local variables that define their methods. These variables are external variables of the anonymous method. There are several important knowledge points about the interaction between anonymous methods and the scope of definition methods: anonymous methods cannot access the ref or out parameters in definition methods. The local variable in the anonymous method cannot be the same as the local variable in the external method. The anonymous method can access instance variables (or static variables) in the external class scope ). 4. What is the Lambda expression used for dry hair? Well, I am totally defeated. I think the anonymous method is still troublesome. It is also troublesome to take off my pants. So it is easier for you to take off your pants. Let's look at my Lambda: write: Lambda expressions are written in this way. First, define a parameter list, and the "=>" mark is followed by the statements that process these parameters. The following expression describes ArgumentsToProcess => StatementsToProcessThem. So how do I express the above registration handler using Lambda expressions? As follows: c1.AboutToBlow + = (sender, e) => {Console. WriteLine ("Eek! Going to fast! "); // The input parameters can be processed in it}; 5. The summary mainly discusses four things, namely, delegate, and then optimize them into events. Then it is simplified to the anonymous method, and finally to the Lambda expression process.