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 ".