How to Create C # Closure ?,

Source: Internet
Author: User

How to Create C # Closure ?,

An important concept in JavaScript is closure. Closure has a large number of applications in JavaScript, but do you know? C # You can also create Closure. The following describes how to create a magic closure in C.

Before that, we must first know how to define functions in C #.

// Function definition. The parameter is string and the return value is string Func <string, string> myFunc = delegate (string msg) {return "Msg:" + msg ;};

Lambda expressions can simplify the above Code, but the effect is the same:

  //Lambda Func<string, string> myFuncSame = msg => "Msg:" + msg;

After defining a function, you can call it:

// Function call string message = myFuncSame ("Hello world ");

Defines a nested function with external variables (relative to embedded functions). External functions return nested functions:

Public static Func <int, int> Func () {var myVar = 1; Func <int, int> inc = delegate (int var1) {// myVar can record the status (value) after the last call. myVar = myVar + 1; return var1 + myVar ;}; return inc ;}

C # Closure is called as follows:

static void CsharpClosures() {     var inc = Func();     Console.WriteLine(inc(5));//7     Console.WriteLine(inc(6));//9 }

When inc (6) is called for the second time, the variable myVar in the function does not reinitialize (var myVar = 1) as it does when the function is called for the first time, but retains the value of the first operation, 2. Therefore, the result returned by inc (6) is (2 + 1 + 6) = 9.

The above motion graphs are provided by "Graph dado ".

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.