Delegate, Lambda expression, event series 05, Action delegate and closure, lambdaaction

Source: Internet
Author: User

Delegate, Lambda expression, event series 05, Action delegate and closure, lambdaaction

Here is an example of using the Action delegate:

        static void Main(string[] args)
        {
            int i = 0;
            Action a = () => i++;
            a();
            a();
            Console.WriteLine(i);
        }

The result is expected 2. But the curious thing is: how is the variable I on the stack passed to the Action delegate?

 

Check the reverse compilation. First, check the IL code corresponding to the Main method:

 

Let's look at the IL code of c_DisplayClass1:

We can see that:
→ An Instance named c_DisplayClass1 is created on the hosting stack.
→ Assign the value of the stack variable I to the instance field I of c_DisplayClass1.
→ Compiler () => I ++; A <Main> B _0 method name is delegated anonymously in the Lambda expression and becomes an instance method of c_DisplayClass1.
→ Assign the instance method <Main> B _0 of c_DisplayClass1 to the delegate variable of Action.
→ The last call to the delegate is twice, both of which are for the instance field I of c_DisplayClass1

 

In other words, an object instance is created on the hosting stack to form a closure ". The variables on the stack become the instance fields of the closure, and the anonymous delegate represented by the Lambda expression becomes the instance method of the closure.

 

Above, an Action is created to form a "closure". Then, two actions are created to form two "closures". Check whether the instance fields of "closure" affect each other?

        static void Main(string[] args)
        {
            Action a = GetAction();
            Action b = GetAction();
Console. Write ("the value of the first call of a and I = ");
            a();
            Console.WriteLine();
Console. Write ("the second call of a, I value = ");
            a();
            Console.WriteLine();
Console. Write ("the value of B, I is called for the first time = ");
            b();
            Console.WriteLine();
        }
        static Action GetAction()
        {
            Action result = null;
            int i = 0;
            result = () => Console.Write(i++);
            return result;          
        }

In the preceding example, although the same GetAction method is assigned to the Action delegate, the GetAction method is in different "closures". When you call the delegate to execute the GetAction method, the instance field I in the closure is automatically increased by 1 and printed.

 

Conclusion: each Action has its own "closure", and "closure" does not affect each other.

 

"Delegation, Lambda expressions, and event series" include:

Delegate, Lambda expression, event series 01, Delegate, basic delegate usage, delegate Method and Target attribute delegate, Lambda expression, event series 02, when should I use delegate, Lambda expression, event series 03, from delegate to Lamda expression?

Delegation, Lambda expressions, event series 04, how the delegation chain is formed, multicast delegation, calling the delegation chain method, delegation chain Exception Handling delegation, Lambda expressions, event series 05, action delegate and closure delegate, Lambda expression, and event series 06. Use Action to implement observer mode and experience the differences between delegate and event
What is Closure )? Answer

This article is translated. This problem was raised in the last Brighton ALT. NET Beers event in England. I found that if you do not need code to demonstrate it, it is difficult to explain it clearly in words. So here, I plan to use C # To explain what closures is ). In computer science, Closure is short for Lexical Closure, a function that references free variables. This referenced free variable will exist with this function, even if it has left the environment where it was created. Therefore, there is another saying that a closure is an entity composed of a function and its reference environment. Therefore, a closure is a function that "captures" or "carries" all variables referenced in the scope of variables in the generated environment. Indeed, it is hard to describe, but it is easy to understand after you have read the code. Var x = 1;
Console. Out. WriteLine ("result = {0}", result) ;}; action (); here we first define a variable "x" with a value of 1. Then we define an anonymous function (a lambda expression) assigned to the type Action. Action has no parameters and no return value. However, if you observe the definition in "action", you will find that it uses the "x" variable. This variable is "captured" or "carried" by the action and is automatically added to the runtime environment of the action. When we execute the action, It outputs the expected results. Note that the original "x" is out of its original variable environment, but it can still be used. When you observe "action" in the Code debugger, you will find interesting things. We can see that the C # compiler creates a Target class for us, which encapsulates the x variable: closure (and higher order functions. If you have developed a Javascript program that is a little more complex, you may know that it can be used as a substitute for many object-oriented features, just like C. Not long ago, I wrote an example in C # To verify this idea. Traditionally, John Skeet gives the closure a more detailed description. For more details, see this chapter in in-depth analysis of C. It also introduces some errors you may encounter in closures. Read: C # What is a closure with a closure? I understand it.

What are commonly used English in computers )?

Computer English Vocabulary
Access arm head arm and inventory arm
Access time
Adder
Address
Alphanumeric
Analog computer simulation computer
Analyst
Area
Array, array
Assembler
Automation
Band Area
Batch processing
Binary code
Binary digit binary bit and binary number
Bit/binary
Branch and branch line
Brush
Buffer storage buffer
Calculator
Call instruction call command
Card punch card punching machine
Card reader and reader
Cell
Channel, channel
Character
Check digit
Circuit, line
To clear and clear
Clock
Code
To code
Coder coders, encoders
Command and command
Compiler Compilation Program
Computer language
Console
Control unit control components and controllers
Core storage and core store core memory
Counter
Cybernetics Control Theory
Cycle
Data
Data processing
Debugging
Describe
Digit number, digit, bit
Digital computer
Disc, disk
Display unit display Device
Drum
To edit
Electronics
Emitter Transmitter
To encode Encoding
To erase erasure, cleaning, and erasing
Feed and Supply
To feed and Supply
Feedback
Field, Information Group, Domain
File
Floppy disk
Floppy disk drive
Flow chart Flowchart
Frame
Hardware
Identifier
Index
Information
Inline processing
Input
Inquiry
Instruction command
Integrated circuit
To interpret explanation
Item project, item
Jump Transfer
Key and key code
Keyboard
Latency time wait time
Library, library
Linkage connection
To load loading, storage, writing, and loading
Location storage unit
Logger registers and recorders
Loop
Machine language
Magnetic storage magnetic memory
Magnetic tape
Matrix
Memory
Message and message
Microcomputer
Module components and modules
Monitor, Monitoring Program,... remaining full text>

Related Article

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.