The following section of C #3.0 code seems to be more common:
Stack stack = StackFactory. New ();
Stack. Push (1 );
Stack. Push (2 );
Stack. Push (3 );
Console. WriteLine (stack. Pop ());
Console. WriteLine (stack. Pop ());
Console. WriteLine (stack. Pop ());
Running result:
> 3
> 2
> 1
However, if I tell you that Stack is not a common class Stack, It is a type alias: using Stack = System. func <T1, R1> is actually a commission. Do you think it is amazing? To be clearer, StackFatory. New () creates a Closure instead of a common object ).
What is a closure?
So what is the closure? There are currently two popular sayings: one is that the closure references the function of free variables in its lexical context; another argument is that a closure is a combination of a function and its reference environment. Both are true, but I prefer the second statement because it clearly defines a closure as an "entity ". From the example, we can see that closures can show the characteristics of objects, while normal lambda functions or delegate are more like a method. Combining the two definitions, I think the closure can be understood as a function with a state.
Free variable
Let's take a simple example of a closure:
Static Func <int, int> AddX (int x ){
Return (y) => x + y;
}
Here, lambda function (y) => x + y is a closure, which references free variable x outside of its lexical context. For AddX (8), the value is replaced by x (y) => 8 + y. If you continue to evaluate AddX (8) (100) 8 + 100 = 108.
Status
Next we will see how to make the closure stateful:
Static Func <int> NewCounter (){
Int x = 0;
Return () => ++ x;
}
Func <int> counter1 = NewCounter ();
Console. WriteLine (counter1 ());
Console. WriteLine (counter1 ());
Console. WriteLine (counter1 ());
Func <int> counter2 = NewCounter ();
Console. WriteLine (counter2 ());
Console. WriteLine (counter2 ());
Console. WriteLine (counter2 ());
Running result:
> 1
> 2
> 3
> 1
> 2
> 3
We created a closure through NewCounter. Every time we evaluate the closure, it will increase the local variable x of its environment by 1, which reflects the closure state. At the same time, we noticed that the local variable x is independent for different closures. counter1 and counter2 do not share the same x.
Closure vs class
Here we can make a comparison with the OOP program. If we want to use classes to implement Counter, what will we do?
Class Counter {// corresponding to NewCounter
Private int x; // corresponding to the local variable int x
Public Counter () {x = 0;} // NewCounter () corresponds to NewCounter ()
Public int Count () {return ++ x;} // corresponding to () => ++ x
}
Is the structure similar to the closure program above? Counter class corresponds to NewCounter function; new Counter () corresponds to NewCounter (); Counter class's private member x corresponds to NewCounter's local variable x; Counter class's Count () the method corresponds to the closure.
Action
In addition to the status, we also need to make the closure have object behavior like stack. Push () and stack. Pop. Since a closure only has one () operator, how can we make it have multiple methods? The answer is Higher-Order Function ). Let's look at the Stack example:
Public enum Method {
Push, Pop, Top
}
Public static Func <Method, object> NewStack (){
Counter list <int> aList = new counter list <int> ();
Func <Method, object> func = (method) => {
Switch (method ){
Case Method. Push:
Action <int> push = (int aValue) => {aList. AddLast (aValue );};
Return push;
Case Method. Pop:
Func <int> pop = () => {
Int value = aList. Last. Value;
AList. RemoveLast ();
Return value;
};
Return pop;
Case Method. Top:
Func <int> top = () =>{ return aList. Last. Value ;};
Return top;
Default:
Return null;
}
};
Return func;
}
NewStack () returns a closure of the Func <Method, object> type. Its parameters are of the enum Method type, and the return value is of the object type. NewStack () (Method. Push) will get:
Action <int> push = (int aValue) => {aList. AddLast (aValue );};
This is the actual Push method! However, you need to explicitly convert the type before calling:
(NewStack () (Method. Push) as Action <int>) (1 );
Finally, we wrap it using the Extension Method of C #3.0 to make the call more concise:
Public static void Push (this Func <Method, object> aStack, int aValue ){
(AStack (Method. Push) as Action <int>) (aValue );
}
Public static int Pop (this Func <Method, object> aStack ){
Return (int) (aStack (Method. Pop) as Func <int> )();
}
Public static int Top (this Func <Method, object> aStack ){
Return (int) (aStack (Method. Top) as Func <int> )();
}
In this way, we can write very OO code like stack. Push (1) and stack. Pop! Through this step-by-step exploration, do you have a deeper understanding of functional programming closures and their relationships with OOP objects?
Mode
We can generalize the method of using closures to create objects in C #3.0 as a fixed pattern.Closure Factory Pattern). The modes include:
1. Define a factory class XXFactory and provide the static factory method New for creating closure objects;
2. Define the local object in the New method as the State m_States of the closure object;
3. Define the enum Method to indicate the Method of the object;
4. Create and return a closureObject that references m_States in the New Method. Its type is Func <Method, object>;
5. closureObject accepts the Method parameter and returns the methodObject representing the closure (or normal delegate) of the Method;
6. Define the extension Method by using the extension Method Func <Method, object>, and add the syntax sugar to the Method call of closureObject.
Reference
Concepts, forms, and applications of closures
The Beauty of Closures