Closures are in. NET implementation (compiler play tricks)-----C # essence on reading notes

Source: Internet
Author: User

I have read many masterpieces since I joined the work. There are a lot of books to read when feeling Taichetaiwu, unconsciously issued ' Oh ... ' Such a sigh. But with the killing of Pig knife (time) constantly flies, not only to my face brought wrinkles, but also took a lot of previous summary and induction of knowledge points and those I have not had time to absorb the valuable wealth. Good memory than rotten pen, I decided to start writing some reading notes and work on the experience, it is best to combine the two, the knowledge of the real self into their own ability.

Let's get down to the chase. Closures are almost ubiquitous in the programmer's daily work, and of course not only the job, but also often the relevant topics during the interview. Have seen a lot of blog friends on the park have explained that every time there are ' Oh ... ' The feeling. Yes, every time ... Perhaps because of my caishuxueqian, some of the great God explained very deeply, and finally summed up too incisive. These days in the review of C # essence (Third edition) (a voice floated over: You have not read before ....) )。 The inside mentions the closure, is only a very small section, said does not calculate ' deep ' (Does not list IL), but definitely is shallow out, this time I really is Taichetaiwu, believed that you must understand after reading.

To better understand the code, a few lines of code are needed to illustrate the implementation of the LAMDA expression (anonymous method). Like closures, they're just a trick for the compiler to play, which makes it a little more fun to use.

Class Program
    {
static void Main (string[] args)
        {
int[] items = new Int[2];
for (int i = 0; i < items. Length; i++)
            {
Console.WriteLine ("Enter A Integer:");
items[i] = Int. Parse (Console.ReadLine ());
            }

var flag = Sort (items, (first, second) = {return first > second;});

if (flag)
Console.WriteLine ("First Parameter is bigger");
Else
Console.WriteLine ("Second Parameter is Bigger");

Console.read ();
        }

static bool Sort (int[] items, func<int,int,bool> method)
        {
return Method (Items[0], items[1]);
        }
    }

The code above is very simple, compare the size of the two input, which uses a lambda expression to pass the comparison method, then after the compiler compiled, the following code shows the compiler produced by the CIL code corresponding to the C # code:

Class Program
    {
static void Main (string[] args)
        {
int[] items = new Int[2];
for (int i = 0; i < items. Length; i++)
            {
Console.WriteLine ("Enter A Integer:");
items[i] = Int. Parse (Console.ReadLine ());
            }

var flag = Sort (items,program.__anonymousmethod_00000000);

if (flag)
Console.WriteLine ("First Parameter is bigger");
Else
Console.WriteLine ("Second Parameter is Bigger");

Console.read ();
        }

static bool Sort (int[] items, func<int,int,bool> method)
        {
return Method (Items[0], items[1]);
        }

   private static bool program.__anonymousmethod_00000000 (

int first, int second)

{

return first < second;

}
}

At a glance, the compiler helped us generate a static function. Someone might ask, what does it have to do with closures? Let's look at another piece of code:

Class Program
    {
static void Main (string[] args)
        {
int comparioncount = 0;
int[] items = new Int[2];
for (int i = 0; i < items. Length; i++)
            {
Console.WriteLine ("Enter A Integer:");
items[i] = Int. Parse (Console.ReadLine ());
            }

var flag = Sort (items, (first, second) = =
            {
comparioncount++;
return first > second;
            });

if (flag)
Console.WriteLine ("First Parameter is bigger");
Else
Console.WriteLine ("Second Parameter is Bigger");
Console.WriteLine (String. Format ("Items were compared {0} times", Comparioncount));
Console.read ();
        }

static bool Sort (int[] items, func<int,int,bool> method)
        {
return Method (Items[0], items[1]);
        }
    }

The above section of code closures appears, inside the function reads the variables defined by the external function. What exactly did the compiler do, let's look at the following code:

Class Program
    {
Private Sealed class class __localsdisplayclass_00000001
        {
public int Comparioncount;
Public bool __anonymousmethd_00000000 (int first,int second)
            {
Comparioncount + +;
return first>second;
            }
        }

static void Main (string[] args)
        {
__localsdisplayclass_00000001 locals =
new __localsdisplayclass_00000001 ();
locals. Comparioncount =0;
int[] items = new Int[2];
for (int i = 0; i < items. Length; i++)
            {
Console.WriteLine ("Enter A Integer:");
items[i] = Int. Parse (Console.ReadLine ());
            }

var flag = Sort (items,locals.__anonymousmethd_00000000);

if (flag)
Console.WriteLine ("First Parameter is bigger");
Else
Console.WriteLine ("Second Parameter is Bigger");
Console.WriteLine (String. Format ("Items were compared {0} times", Comparioncount));
Console.read ();
        }

static bool Sort (int[] items, func<int,int,bool> method)
        {
return Method (Items[0], items[1]);
        }
    }

The used local variable is treated as an instance field, which is included in the compiler-generated inner class.

The resulting __localsdisplayclass class becomes a closure, which is a data structure (a C # Class) that contains an expression and the variables that are required to evaluate an expression.

After believing that the code is posted, there is no need to explain it too much. There are some best practices and recommendations for C # essentialism that will be sorted out in succession. Re-recommend this book, because the experience and the basis of the different, everyone, each time to see the feelings and focus will be different.

Of course, the first blog, to leave a memorial. Thank my wife for my understanding, allow me to Spring Festival a person nest in the home (no hometown for the new Year), there is ample time to play while watching while learning, your support and understanding, is the driving force of my progress!!!

Implementation of

Closures under. NET (compiler play tricks)-----C # essence on reading notes

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.