Lambda expressions and anonymous methods in. net

Source: Internet
Author: User
Document directory
  • I. func <……> Generic delegation type
  • 2. Step 1 of converting to a Lambda expression
  • 3. Use a single expression as the function body
  • Iv. List of implicit Parameters
  • 5. Remove the brackets on both sides of a single parameter.
  • Vi. Summary

In C #2, the use of delegate makes it easy to use due to the association and resistance of method groups, anonymous methods, and types, and the code becomes easy to read in the event registration era, but in C #2, the code is still a little bloated, and the large anonymous method will reduce the readability of the Code. Generally, we do not write Multiple anonymous methods in one statement.

One of the purposes produced by LINQ is to facilitate data pipeline operations without losing semantics. LINQ can express various logical operations on data. These operations are actually implemented through delegation during the execution of LINQ. When using LINQ to object to operate data, it is very common that a statement contains multiple delegates. The Lambda expression in C #3 is the hero behind the scenes, it not only enables us to write multiple delegates in one code, but also does not lose the readability of the Code. I believe that anyone who has used LINQ should have such experiences.

Lambda expressions can be viewed as the evolution of anonymous methods in C #2. Both of them have the same functionality, making the code clearer and more compact. In addition, lambda expressions and anonymous methods are consistent in the characteristics of closures, but lambda expressions also have some small features that make the code more compact in most cases. Like Anonymous methods, lambda expressions have their own conversion rules-the expression type is not a delegate type, but it can be displayed or implicitly converted to a delegated instance.

Let's take a look at how lambda expressions represent delegation. Let's start with a simple example. First, we write a delegate instance that takes the string type as the parameter and returns the int32 type value. Then demonstrate how to convert a delegate to a Lambda expression step by step.

 

I. func <……> Generic delegation type

First, we need to select the delegate type. In. Net 3.5, a series of generic delegation types are provided. In. net3.5, there are five generic Delegate types named func. Each type contains 0 to 4 type parameters. Five func generic signatures are as follows:

TResult Func<TResult>()TResult Func<T,TResult>(T arg)TResult Func<T1,T2,TResult>(T1 arg1, T2 arg2)TResult Func<T1,T2,T3,TResult>(T1 arg1, T2 arg2, T3 arg3)TResult Func<T1,T2,T3,T4,TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)

All parameters in angle brackets are type parameters. For example, func <string, double, int32> indicates that the delegate accepts two parameters. The first parameter is string, and the second parameter is double. int32 type is returned, you can use this delegate for all methods that suit this type. Func <string, double, int32> is equivalent to the following delegate:

public delegate Int32 SomeDelegate(String arg1, Double arg2)

In. Net 3.5, there is also an action named <...> Is similar to func, but its return value is void. If you think five parameters are not enough, in. Net 4.0, Action <……> And func <……> To 16 parameters, such as func <t1 ,......, T16, tresult>, so many parameters are mainly used to support DLR.

In this example, we need a type that accepts string as the parameter and returns the int32 value. Therefore, we can use func <string, int32>.

2. Step 1 of converting to a Lambda expression

Based on the above delegate type, we can use the anonymous method to create a delegate instance. The instance returns the length of the string parameter.

Func<String, Int32> returnLength;returnLength = delegate(String text) { return text.Length; };Console.WriteLine(returnLength("Hello"));

In the above example, the output is 5. The above expression starting with delegate is an anonymous expression. Now we start to convert this part. The most common lambda expressions are as follows:

(Parameter type 1 parameter name 1 [, parameter type 2 parameter name 2...]) =>{ Internal expression of the method}

=> It was introduced in C #3. He told the compiler that we will use lambda expressions, and most of them use lambda expressions to indicate that the delegate method has a return value. However, in C #1, delegation is usually used for events, so there are very few returned values. In LINQ, the delegate is used as a part of the data pipeline, allowing data to perform various ing, filtering, and other operations.

The following code uses a Lambda expression to represent the instance of the delegate:

Func<String, Int32> returnLength;returnLength = (String text)=> { return text.Length; };Console.WriteLine(returnLength("Hello"));

The results returned in the preceding example are the same as those previously returned. In braces, we can write any expression as long as the return value is of the string type.

3. Use a single expression as the function body

In the previous example, we used a pair of braces to enclose the return value expression. This is flexible. You can write multiple statements in parentheses to perform various operations, just as in the anonymous method. However, in most cases, the function body can be expressed as a single expression. The value of this expression is the value of the lambda expression. In this case, we can save the braces and commas (,) between the left and right. The expressions look like the following.

(Parameter type 1 parameter name 1 [, parameter type 2 parameter name 2...]) => Method Expression

In this way, the right part of the above example can be rewritten:

returnLength = (String text) => text.Length;

It seems much simpler now. What about the parameter type? Because the compiler already knows that it is an instance of func <string, int32>, this instance accepts a string type parameter, therefore, we can directly unmount the parameter from the brackets to omit the parameter type.

Iv. List of implicit Parameters

In most cases, the compiler can deduce the parameter type without actual declarations. Therefore, lambda expressions can be rewritten:

(Parameter name 1 [, parameter name 2...]) => Method Expression

The list of implicit parameters is a series of parameter names separated by commas. Either all of these parameter types display the Declaration type, or all do not declare the type for the compiler to infer, not part of the display declaration, part of the implicit declaration. If the parameter type is out or in, the declared parameter type must be displayed. In this way, our Lambda expression can be rewritten:

returnLength = (text) => text.Length;

It seems much simpler now. The last unpleasant thing is that the parameter has parentheses.

5. Remove the brackets on both sides of a single parameter.

When the lambda expression has only one parameter value, we omit the parentheses for running C #3. The entire Lambda expression is in the following format:

Parameter Name => Method Expression

According to this rule, the lambda expression in the previous example can be changed:

returnLength = text => text.Length;

You may think that there are so many special examples, there is exactly one parameter, and the function topic can be expressed in one expression. This is to demonstrate how lambda expressions simplify code to improve readability. In many cases, lambda expressions can greatly improve code readability when a large number of such cases occur. Now the entire method can be written as follows:

Func<String, Int32> returnLength;returnLength = text => text.Length;Console.WriteLine(returnLength("Hello"));

It seems much more concise now. It may be the first time I think it is strange to write this code. Just like the first time I used the anonymous method and LINQ, I got used to it after a long time. When using lambda expressions, you can understand the conciseness of creating a delegated instance. In the above example, we can change the variable Text to another name, such as X, which is often used in LINQ, but a longer variable can be easier to read. The above steps are summarized:

 

Vi. Summary

This article uses a special case to demonstrate how to convert an anonymous method to a Lambda expression step by step. From the conversion, you can understand the simplicity of lambda expressions. I hope this will be helpful for you to understand lambda expressions.

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.