9. Delegates, events, LAMBDA

Source: Internet
Author: User

there must be a problem with the delegation.
First question, what is the delegate used for? Look at the expression in. NET: Under the. NET platform, the delegate type is used to define and callback in the corresponding application. Callback A technique for handling bidirectional communication between two entities in memory. The second question, delegate and C + + (actually originates from the C language) function pointers? It is necessary to say the difference, although both the delegate and the function pointers point to the method to be called later. But a delegate has two advantages over a function pointer: one, the delegate is the object (we know that the delegate and the class are at one level). Second, the delegate is built-in to support multicast and asynchronous method calls.
about events.
Question, what is the event used for? Events are services for delegates, which makes our process of handling delegate types more streamlined and efficient.
about Lambda.
Question, what is this thing doing again? Lambda uses the operator = = to let us invoke the delegate, but it's simpler.  ok, it seems, this is inseparable from the Commission, know what the Commission is a thing, you can understand the event and what Lambda is.   A. NET delegate type before the callback function, C in the function pointer, that is, a point in memory a piece of address done. We do not know more about the type of information, such as what type, what return value, Mother egg, all a smear. The delegation came out and felt that the previous set of callbacks was unsafe, so I became a type-safe object, pointing to a method that would be called later in the program (can be multiple. Wayward!  1. What can a delegate contain? After all this stuff, is it good for God horse? The name of the function method it calls; The parameter of the method (optional); The return value of the method (optional). With these, at run time I can invoke the method pointed to dynamically. As a result, this delegate automatically has the ability to synchronize or a method of access, it is not necessary to invoke the thread of the auxiliary method, is to simplify the programming work.  2. What did the Commission do? Definition: public delegate int BINARYOP (int x, int y); Represents a method that points to an integer that is returned by an operation of two integers. When compiling, the delegate will become the east of three public methods, three methods: Invoke, BeginInvoke, EndInvoke method, the first one for synchronous invocation, and the latter two asynchronous invocations. A different pace is typically used to invoke a more time-consuming method. (When we write the interface, we often use it to prevent interface cards from being invoked asynchronously, without affecting the movement of the interface and other operations.) In memory their representations are often as follows (where an underscore is a red line that can be written as a return type and a parameter type (regardless of the number)): The pseudo-code above can be seen, the delegate is actually and class at a level of things, it also has a base class, Two base classes: System.MulticastDelegate and System.Delegate base classes.   Simple Delegate instance (two number addition): How to do? The delegate is at the bottom, and the compiler-generated invoke method is actually called on the MulticastDelegate derived class. The following is the type safety of the delegate: If you attempt to pass a mismatched method to the delegate, you will receive a compilation error (such as the method above that delegates you to pass in a parameter).  3. How do I send object notifications? Define a car class whose public members are as follows: Define the delegate to determine if the maximum value will crash when accelerating: here is the acceleration method, which outputs a number of different information when the speed is different: each acceleration of 20 in the main method of the program, and the recording of each additionalOutput after speed: The result of the call is as follows: From the top, you can summarize the steps of the delegate notification: Define the delegate type that sends the notification to the caller. Declare each delegate type member variable. In tears. Creating an auxiliary function enables the caller to specify a method that is saved by a delegate member variable. Modify the method to invoke the invocation list in the delegate in the appropriate scenario.   What's going on with the multi-channel broadcast? This means that a delegate object can maintain a list of callable methods, not just a single method. How? The + = and-= operators are involved. The above delegate invocation method writes another: Method modification in CAR: Call code: Result: Similarly, if you want to remove a method, use the-= operator. Equivalent to the UNSUBSCRIBE function.  4. Method group Conversion Syntax C # provides methods for group conversion syntax, which facilitates delegate operations, allowing us to provide the name of the method directly when invoking the method of the delegate as a parameter, rather than creating a delegate object. For example, the process of creating a delegate object above can be saved and become the following code:  C1. Registwithcarengine (OnCarEngineEvent2);  5. Delegated covariant take the car for example, if we derive a Newcar class and create a delegate type, you can point to the method that returns the class. Because the delegate is a security type, we cannot use a delegate that returns a car, and a new delegate must be defined. The delegate covariance is a method that allows us to create a delegate that can point to the return class and the associated inheritance system. We can cast the result of the previous delegate, which returns to car, for casting. Cardelegate car = new Cardelegate (new Newcar (XXX)); When used, 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 invoke any method that returns void and accepts a single argument. If this parameter may be different, we can build it with the type parameter. Generic delegates provide a more flexible way to specify the type-safe method of invocation. Before, we generally achieve similar purposes by using the System.Object parameter: public delegate void MyDelegate (object arg); However, we lose type safety and may have a boxing loss.   Second, C # events use the delegate will encounter problems. (Destruction of encapsulation) when we do not define a delegate as private, the caller can directly access the delegate object, so that the caller can also re-assign the variable to the new delegate object. ooops! The problem arises. The previous method is equivalent to deleting and callingYou can also invoke the invocation list of the delegate directly. In a word: Public members break the encapsulation, which not only causes the code to be difficult to maintain and debug, but also leads to an application's security risk.  1. Is the event dry hair? How do you do that? It says the problem, the event is out, you can know, the event is to do this thing. (Packing the delegate so that it does not break the encapsulation). How did that come about? When the compiler processes the event keyword, it automatically provides the registration and logoff methods and any necessary delegate type member variables (seemingly simplifying the delegate), and these delegate member variables always private , so it is not possible to access them from the object that triggered the event (ooh, secure). Usage of the event: The following is the accelerated method after the modification:  2. So how does an event encapsulate a delegate? (in addition to the default, the delegate is set to private, and the following encapsulation) add_ and remove_ prefixes. For example, the Abouttoblow event above is encapsulated in the CIL code as follows: As a result, the event simply saves typing events, and here's how to listen for incoming events on the caller's side. C # Events also simplify the process of registering the caller event handler. There is now no need to specify a custom helper method, the caller only needs to use the + = and-= operators (the operator will trigger the correct add_xxx () method or the Remove_xxx () method in the background). Use the C # event registration syntax to modify the main method as follows: Of course, we can also use method groups to convert syntax. is no longer stated.  3. Create a custom event argument. What is Microsoft's recommended event pattern? When you view an event sent by a type in the underlying class library, you 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 a base class that represents an event that does not send any custom information: So if we are going to pass custom data, we need to create a class that derives from EventArgs. As follows: We modify the delegate, add a Careventargs parameter, we can pass the data. (The event does not change.) public delegate void Carenginehandler (object sender, Careventargs args);//define delegate invocation method:          &N Bsp     if (exploded! = null)                 {        &N Bsp           exploded (this,new Careventargs ("Sorry, this car is dead ..."));      &NBS P         How the recipient wants to interact with the object that sent the event, we can realistically cast the system.Object. This allows you to use any public member that is passed to the event through the object.   C # Anonymous method anonymous method is dry hair again? This is really a wave, first of all to solve the function of the pointer is not security, but later too troublesome, and there are events. As a result, the event seems to be nagging, OK, anonymous method debut: The above registered event handler was changed to:            C1. Abouttoblow + = Delegate (Object Sender,careventargs e)             {      &NBS P         Console.WriteLine ("Eek! Going to fast! ");            }; it looks as if the processing and registration declarations have come together. Description: The last curly brace in an anonymous method must end with a good score, otherwise a compilation error will be generated. Here is the pseudo-code for the syntax of an anonymous method: The anonymous method is very interesting, and it allows us to access local variables that define their methods. These variables become external variables of the anonymous method. There are several important points of knowledge about the interaction between anonymous methods and the scopes that define methods: Anonymous methods cannot access the ref or out parameters in the definition method. A local variable in an anonymous method cannot have the same name as a local variable in an external method. Anonymous methods can access instance variables (or static variables) in the scope of an external class.   Lambda expression lambda expression is used for dry hair? Well, completely defeated, think Anonymous method also trouble, all put pants off still too trouble, so let you take off pants also simple, see my lambda bar: write: Lambda expression is written like this, first, define a parameter list, the "= =" tag is immediately followed, Then there is the statement that handles these parameters. The following expression can be described as: Argumentstoprocess=>statementstoprocessthem. So how do you express the above registration handler with a lambda expression? as follows: C1. Abouttoblow + = (sender,e) =>{ console.writeline ("eek! Going to fast! "); /inside can handle incoming parameters  };  v. Summary This is a discussion of fourSomething, in fact, is one, and that is the delegate and then the optimization into the event. It then simplifies the process of becoming an anonymous method and finally simplifying it into a lambda expression.

9, delegate, event, Lambda

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.