C # lambda expressions,

Source: Internet
Author: User

C # lambda expressions,

From C #3.0, you can use lambda expressions to delegate the implementation code. Lambda expressions are directly related to delegation (http://www.cnblogs.com/afei-24/p/6762442.html. When a parameter is of the delegate type, you can use a lambda expression to implement the delegate reference.

    

        static void Main()        {              string mid = ", middle part,";              Func<string, string> anonDel =  param =>              {                param += mid;                param += " and this was added to the string.";                return param;              };              Console.WriteLine(anonDel("Start of string"));        }

 

The parameter list is on the left of the lambda operator "=>", and the implementation code of the lambda variable method is on the right.

1. Parameters
If the lambda expression has only one parameter, only the parameter name can be written, as shown in the code above.

If multiple parameters are used in the delegate, you need to put the parameter names in brackets:
Func <double, double, double> twoParams = (x, y) => x * y;
Console. WriteLine (twoParams (3, 2 ));

You can add the parameter type to the variable name in brackets:
Func <double, double, double> twoParamsWithTypes = (double x, double y) => x * y;
Console. WriteLine (twoParamsWithTypes (4, 2 ));

2. Multi-line code
If a lambda expression has only one statement, no curly brackets or return statements are required in the method block, because the compiler adds an invisible return statement.
Func <double, double, double> twoParams = (x, y) => x * y;

Func <double, double, double> twoParams = (x, y) =>
{
Retrun x * y;
}
If there are multiple statements in the implementation code of lambda expressions, you must add curly brackets and return statements:
Func <string, string> anonDel = param =>
{
Param + = mid;
Param + = "and this was added to the string .";
Return param;
};

3. Closure
Lambda expressions allow you to access the external variables of the lambda expression block, which is called closures. Closures are good functions, but they are dangerous if used improperly. For example:
Int someVal = 5;
Func <int, int> f = x => x + someVal;
If the someVal variable is modified later, the new value of someVa will be used when the delegate f is called:
SomeVal = 7;
F (3); // The result is 10 instead of 8.
In particular, when we call a lambda expression through another thread, we may not know whether to call the lambda expression or what the current value of the external variable is.
So be careful when using closures !!!

When a lambda expression accesses a variable outside the lambda expression block, the compiler creates an anonymous class when defining the lambda expression. It uses a constructor to transmit the external variable. The constructor depends on the number and type of variables passed in from the outside.
For lambda expressions Func <int, int> f = x => x + someVal;

    public class AnonymousClass        {            private int someVal;            public AnonymousClass(int someVal)            {                this.someVal = someVal;            }                        public int AnonymousMethod(int x)            {                retrun x+someVal;            }        }

When lambda expressions are used and the method is called, an instance of the anonymous class is created and the variable value when the method is called is passed.

4. Use the closure of the foreach statement
Let's take a look at the following example:
Var values = new List <int> () {10, 20, 30 };
Var funcs = new List <Func <int> ();

Foreach (var val in values)
{
Funcs. Add () => val );
}

Foreach (var f in funcs)
{
Console. WriteLine (f ()));
}

The first foreach statement adds each element in the funcs list. Functions added to the List use lambda expressions. The lambda expression uses a variable val, which is defined as a loop variable of the foreach statement outside the lambda expression. The second foreach statement iterates the funcs list to call each function referenced in the list.
When compiling this code in C #5.0 or earlier, it will be output 30 times on the console. This is because the closure is used in the first foreach loop. The created function obtains the value of the val variable during the call rather than iteration. In. In versions earlier than C #5.0, the compiler defines the loop variable outside the while loop and re-uses this variable in each iteration. Therefore, at the end of the loop, the value of this variable is the value of the last iteration. To use versions earlier than C #5.0 and output 10, 20, 30, you need to change the code to use a local variable:
Var values = new List <int> () {10, 20, 30 };
Var funcs = new List <Func <int> ();

Foreach (var val in values)
{
Var v = val;
Funcs. Add () => v );
}

Foreach (var f in funcs)
{
Console. WriteLine (f ()));
}

In C #5.0, you no longer need to modify the code. C #5.0 creates a different local loop variable in the while LOOP code.

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.