[Transfer] http://blog.csdn.net/maotin/archive/2008/10/20/3110451.aspx
C #3.0 New Experience (5)
Maotin
20081011
Preface:
No matter how high the mountains are, they all climb up one step at a time, because one step can only be taken in a down-to-earth manner. However, we can control the frequency of the steps, which is fast and fast, it is better than others to go to the top of the hill; work and life are also the case, efficiency is fast, and will be closer to success.
Vi. Lambda expressions
1. What is a Lambda expression?
A Lambda expression is an anonymous function that can contain expressions and statements and can be used to create a delegate or expression directory tree. All lambda expressions use the lambda Operator=>The operator reads "goes ". The left side of the lambda operator is the input parameter (if any), and the right side contains the expression or statement block.
Lambda expression: x => X * x
To understand lambda, we need to first look at anonymous functions. What are anonymous functions? An anonymous function is an "inline" statement or expression that can be used wherever the delegate type is required. There are two types of anonymous functions: lambda expressions (C #3.0) and anonymous methods (C #2.0). This "inline" does not seem to be well understood, therefore, the generation and use of anonymous functions are described in detail starting from the use history of delegation:
(Delegate is a type of packaging method call. Just like the type, you can pass the delegate instance between methods and call the delegate instance just like the method .)
C #1.0: Before 2.0, the only way to declare a delegate is to use the naming method, that is, to create a delegate instance by explicitly initializing the delegate using a method defined elsewhere in the Code; for example:
// Declare a delegate
Delegate void testdelegate (string S );
Class testclass
{
Static void main ()
{
// Original delegate syntax required
// Initialization with a named method.
Testdelegate testdela = new testdelegate (testclass. dowork );
// Invoke the delegates.
Testdela ("hello .");
}
// The method associated with the named delegate:
Static void dowork (string K)
{
System. Console. writeline (k );
}
}
C #2.0: In 2.0, the concept of anonymous method was introduced as a way to write untitled inline statement blocks that can be executed in a delegate call, that is to say, you do not need to create a separate method in advance, so the coding system overhead required to instantiate the delegate is reduced, for example: // declare a delegate
Delegate void testdelegate (string S );
Class testclass
{
Static void main ()
{
// C #2.0: A delegate can be initialized
// Inline code, called an "anonymous method." This
// Method takes a string as an input parameter.
Testdelegate testdelb = delegate (string s) {console. writeline (s );};
// Invoke the delegates.
Testdelb ("Hello 2 ");
}
}
C #3.0: introduces lambda expressions, which are similar to anonymous methods but more expressive and concise. Lambda expressions gradually replace anonymous methods as the preferred method for writing Inline code. Example: // declare a delegate
Delegate void testdelegate (string S );
Class testclass
{
Static void main ()
{
// C #3.0. A delegate can be initialized
// A Lambda expression. The Lambda also takes a string
// As an input parameter (X). The type of X is inferred by the compiler.
Testdelegate testdelc = (x) => {console. writeline (x );};
// Invoke the delegates.
Testdelc ("Hello 3 .");
}
}
2. Lambda expression format:
(Parameter list) => expression or statement block. The parameter list on the Left can have multiple parameters, one parameter, or no parameter. The parameter type can be implicit or explicit. For example:
(X, y) => X * y // multiple parameters, implicit type => Expression
X => X * 10 // single parameter, implicit type => Expression
X =>{ return x * 10;} // single parameter, implicit type => statement Block
(Int x) => X * 10 // single parameter, explicit type => Expression
(Int x) =>{ return x * 10;} // single parameter, explicit type => statement Block
() => Console. writeline () // No Parameters
From the above statements, we can draw some key points of the lambda expression:
A. the parameter type can be ignored because it can be inferred based on the context;
// Declare a delegate
Delegate void testdelegate (string S );
Class testclass
{
Static void main ()
{
// From the parameter defined by the delegate, we can infer that X is of the string type.
Testdelegate testdelc = (x) => {console. writeline (x );};
}
}
B. The subject of the expression can be the expression (x, y) => X * Y) or the statement block (x => {return x * 10 ;})
C. The arguments passed in by lambda expressions will be involved in type inference and method overload analysis.
D. Lambda expression expressions and expression bodies can be converted into expression trees.
3. Lambda expressions and delegate types
// Declare a delegate
Public Delegate int testintdelegate (int g );
Class testclass
{
Static void main ()
{
// Pass the lambda expression
Test (y => y * y );
}
Public void test (testintdelegate Ti)
{
Int area = Ti (10 );
}
}
The test parameter of the method is to delegate the testintdelegate type, and we directly input the lambda expression test (y => y * Y) during the call. Therefore, the lambda expression can be converted to the delegate type, however, the following requirements must be met:
A. the number of parameters is the same.
B. The parameter types are the same. Note that implicit types must be involved in type discrimination.
C. The return type of the delegate must be the same as that of Lambda, whether it is an expression or a statement block.
4. Lambda expressions and Expression Tree
The typical Declaration Form of the Expression Tree is 1: func <int, int> func = input => input * input;
2: expression <func <int, int> Expression = input => input * input;
Here we needSystem. LINQ. ExpressionsIn the namespace, expression <t>, and T is the type of the delegate that defines the expression signature. Let's look at the complete code used in the Expression Tree:
1: static void Main(string[] args)
2: {
3: Func<int, int> func = input => input * input;
4: Console.WriteLine(func(3).ToString());
5:
6: Expression<Func<int, int>> expression = input => input * input;
7: Func<int, int> fun = expression.Compile();
8: Console.WriteLine(fun(5).ToString());
9:
10: Console.ReadLine();
11: }
The Expression Tree is used to describe the expression. An advanced tree is provided to represent an expression. Therefore, you can simply understand the purpose of a user expression;
Use Expression Tree:
A. expressions can be converted into delegates and called.
B. Convert the expressions to SQL so that they can be executed by the server (this is done by LINQ to SQL)
C. Convert the expressions to XML and write them to the disk. Convert an expression to a custom format. You can use the network protocol to relax the expression to the server, create a new expression tree, and then execute and/or (and/or) according to it ).
By using Lambda's support for the Expression Tree and the iqueryable <t> interface, a framework developer who builds a data provider can ensure that developers write clean code, it runs fast and efficient on any data source (such as databases, XML files, in-memory objects, Web Services, and LDAP systems.
5. Summary
Generally, the anonymous method replaces the lambda expression, and only uses the lambda expression when the statements have less functions. Otherwise, the written code may be less readable, this will cause unnecessary trouble for future maintenance and modification. Lambda is widely used in LINQ. As the learning progresses, lambda expressions and expression trees are constantly supplemented and corrected.
Refer:Anonymous functions (C # programming guide)
Lambda expressions (C # programming guide)
Anonymous method (C # programming guide)
Expression and Expression Tree reference:
Http://blog.joycode.com/scottgu/archive/2007/04/09/100744.aspx
Http://www.cnblogs.com/GSonOVB/archive/2008/08/29/1279315.html
HTtp: // www.cnblogs.com/autumoon/archive/2007/11/20/964996.html