C # functional programming-Data encapsulation with closures

Source: Internet
Author: User

If a programming language can solve the problem with a higher-order function, it means that the problem of data scope has become very prominent. When a function can be passed between a function as a parameter and a return value, the compiler uses the closure to extend the scope of the variable to ensure that the required data can be obtained at any time. The scope of C # functional programming is in C #, and the scope of variables is strictly determined. In essence, all codes survive in class methods, and all variables survive only in the declared modules or subsequent code. Variable values are variable. The more public a variable is, the more serious the problem is. The general principle is that it is best to keep the value of a variable unchanged, or save its value in the smallest scope. A pure function is best to use only the variable values defined in its own module, without accessing any variables outside its scope. Unfortunately, sometimes we cannot limit the variable value to the function range. What if several variables are defined during program initialization and need to be used repeatedly? One possible method is to use closures. C # functional programming closure mechanism in order to understand the nature of closure, we analyze several examples of using closure: namespace Closures {class Closures {static void Closures () {Console. writeLine (GetClosureFunc () (30);} static Func <int, int> GetClosureFunc () {int val = 10; Func <int, int> internalAdd = x => x + val; Console. writeLine (internalAdd (10); val = 30; Console. writeLine (internalAdd (10); return internalAdd ;}} what is the result output of this code? The answer is 20 40 60. We can see the first two values easily, but why is the third value 60? Let's take a look at the execution process of the program: The Closures function calls the GetClosureFunc function and enters it. A parameter 30 is included in the function call statement. This is because GetClosureFunc returns a function, that is, it calls this function again during execution and enters the GetClosureFunc function. First, the val value is 10, and a value 10 is input through the internalAdd method, therefore, the first output value is 20, go down, the val value is changed to 30, and the value is 10 through the internalAdd method, so the second output value is 40. Here we can roughly see how local functions and local variables play a role in the same scope. Obviously, changes to local variables will affect the value of internalAdd, although the variable changes occur after internalAdd is initially created. Finally, GetClosureFunc returns the internalAdd method and calls this function again with the parameter 30. Therefore, the result is 60. It seems that this is not really logical. Val should be a local variable that lives in the stack. When the GetClosureFunc function returns, it will not be there, will it? Indeed, this is exactly the purpose of the closure. When the compiler will clearly warn that this situation will cause the program to crash, it will prevent the variable value from going out of its scope. From a technical point of view, the data storage location is very important. The Compiler creates an anonymous class and creates an instance of this class in GetClosureFunc -- if closure is not required, then the anonymous function will only survive in the same class as GetClosureFunc. Finally, the local variable val is not actually a local variable, but a field in the anonymous class. The result is that internalAdd can now reference functions stored in an anonymous class instance. This instance also contains the data of the variable val. As long as the reference of internalAdd is maintained, the val value of the variable is always saved. The following code describes the mode used by the compiler in this situation: private sealed class DisplayClass {public int val; public int AnonymousFunc (int x) {return x + this. val;} private static Func <int, int> GetClosureFunc () {DisplayClass displayClass = new DisplayClass (); displayClass. val = 10; Func <int, int> internalAdd = displayClass. anonymousFunc; Console. writeLine (internalAdd (10); displayClass. val = 30; Console. writeLine (internalAdd (10 ); Return internalAdd;} return to the idea of dynamically creating a function: Now you can create a new function out of thin air, and its functions vary with parameters. For example, the following function adds a static value to a parameter: private static void DynamicAdd () {var add5 = GetAddX (5); var add10 = GetAddX (10); Console. writeLine (add5 (10); Console. writeLine (add10 (10);} private static Func <int, int> GetAddX (int staticVal) {return x => staticVal + x ;} this principle is the foundation of many function construction technologies. This method obviously corresponds to object-oriented methods such as method overloading. However, unlike method overloading, the creation of an anonymous function can occur dynamically at runtime, and only needs to be triggered by a line of code in another function. Special functions used to make an algorithm easier to read and write can be created in the method called, instead of adding functions or methods randomly at the class level-this is the core idea of function modularization.

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.