Evolution of Delegate, anonymous method, and Lambda expression

Source: Internet
Author: User

Suppose we have a generic object list <t> and T is of the int type. We need to use this object method findall (predicate <t> match) to find the even number in the list, how do you implement it?

Description: predicate <t> is a generic delegate. Its prototype is public delegate bool predicate <t> (t obj). This delegate is used to input a T-type object, A boolean value is returned after logical judgment.

Delegate

The first thing you may think of is delegate implementation. The implementation method is as follows:

// Method 1
Static Void Method1 ()
{
// Create a list <int> Object
List < Int > List = New List < Int > ();
List. addrange ( New Int [] { 1 , 2 , 3 , 4 , 5 , 6 });

// define a DeleGate
predicate int callback = New predicate int (isevennumber );
// run the findall method, this method uses the incoming delegate callback to determine whether the integer in the list is an even number
List int evennumbers = List. findall (callback);

// Output
Foreach(IntIInEvennumbers)
{
Console. Write (" {0: 0} ", I );
}

Console. writeline ();
}

// Determines whether the input integer is an even number.
Static BoolIsevennumber (IntI)
{
ReturnI %2=0;
}Copy code

This method is good, simple, and intuitive. What are some of them?CodeIt seems a little cumbersome. We only need to execute a judgment statement like "I % 2 = 0", but we need to define a method and a delegate for this statement. If this method is not used elsewhere, is there any way to save it? (of course it is not really omitted. After compilation, this method actually exists, the purpose is at least not to let us enter a method and a delegate for this statement )? Now, our anonymous method is coming soon!

Anonymous Method

See the following code:

Static Void Method2 ()
{
// Create a list <int> Object
List < Int > List = New List < Int > ();
List. addrange ( New Int [] { 1 , 2 , 3 , 4 , 5 , 6 });

// Create an anonymous method and pass it to the findall method.
List <Int> Evennumbers = List. findall
(
Delegate(IntI)
{
ReturnI %2=0
;
}

);

// Output
Foreach(IntIInEvennumbers)
{
Console. Write (" {0: 0} ", I );
}

Console. writeline ();
}Copy code

In the above exampleDelegate(IntI ){ReturnI %2=0;} The statement creates an inline anonymous method delegate and passes it to findall to determine whether an integer in the list is an even number. Compared with Method1, we do not need to define a method and a delegate. The code is much reduced, but is it awkward? What is the prototype of this anonymous method?

A little analysis. (Int I) is the parameter list of the defined anonymous method. Return returns a Boolean value, which is the return value of the method. In this case, the delegate prototype of our inline anonymous method is:

Delegate bool anonymous (int I)

Looks familiar! This is not the same as the predicate <t> prototype Public Delegate bool predicate <t> (t obj). T is the same after it is substituted into the int type! Yeah, that's a coincidence! No, unfortunately not. If the prototype of the anonymous method you defined is not the same, the compiler will directly report an error! The list <int>. findall method requires a predicate <t> delegate!

Well, the delegate definition syntax of the inline anonymous method is like this:

Delegate (Parameter list)
{
Execution statement
} Copy code

Lambda expressions

The implementation of the anonymous method is concise enough. Is there any more concise syntax to implement it? What? Concise? The syntax of the anonymous method is almost dizzy. I need to use a concise method. Some BT! That's how Microsoft Works. Let's take a look at the more BT lambda expressions. The code above:

Static Void Method3 ()
{
// Create a list <int> Object
List < Int > List = New List < Int > ();
List. addrange ( New Int [] { 1 , 2 , 3 , 4 , 5 , 6 });

// Create a Lambda expression and pass it to the findall Method
List < Int > Evennumbers = List. findall
(
( IntX) => {ReturnX %2=0;} // Note: Oh, this is the well-known Lambda expression.
);

// Output
Foreach(IntIInEvennumbers)
{
Console. Write (" {0: 0} ", I );
}

Console. writeline ();
}Copy code

See this line of code: (int x) =>{ return X % 2 = 0 ;}

What is this? Lambda expressions? Right!

Let's analyze the syntax of lambda expressions: Ignore the "=>" symbol first. Lambda expressions are divided into two parts by the symbol. The first half of the symbol is the parameter list, and the second half is the execution statement. to simplify it, the following is the result:

Parameter List => execution statement

Familiar? Well, it seems like, probably, seems, yes, because, so it's a little familiar. By the way, isn't this structure just like an anonymous method? Let's look back at the syntax of the anonymous method:

Delegate (parameter list) {execution statement}

As you can see, lambda expressions are anonymous methods! The difference is that the parameter list and execution statement are separated by the "=>" symbol. In this case, the statement (int x) =>{ return X % 2 = 0;} is just a delegate that passes in an inline anonymous method for findall, the parameter list of this method is (int x), and a Boolean value is returned.

So far, is it worth celebrating? We seem to have started to understand this bt Lambda expression. Now we should call it xiao'er. I don't want to see this confusing code anymore. However, don't be happy first. Microsoft said again. This is not the most concise! What? Isn't it concise? So you can write a more concise look? Second, add the following code:

 

Static Void Method4 ()
{
// Create a list <int> Object
List < Int > List = New List < Int > ();
List. addrange ( New Int [] { 1 , 2 , 3 , 4 , 5 , 6 });

// Create a Lambda expression and pass it to the findall Method
List < Int > Evennumbers = List. findall
(
X => X %2=0 // Is there something speechless here?
);

// Output
Foreach(IntIInEvennumbers)
{
Console. Write (" {0: 0} ", I );
}

Console. writeline ();
}Copy code

 

? Look at this:

X => X % 2 = 0

This is the second time we see the lambda expression. Just remember the syntax of the lambda expression :(Parameter List => execution statement. X is the parameter list in this formula. Why is X not connected to any parameter type? Because the compiler knows that the prototype of the method to be passed in is bool predicate <int> (int obj), it automatically considers the type of parameter X as Int. Similarly, the compiler also knows that the return value of the method is Boolean, And the execution statement (X % 2 = 0) is a Boolean expression. Therefore, the compiler also thinks that we want to return this expression. Finally, the lambda expression is like the little ones whose clothes are stripped away. It is streaking in our code. Well, it's good. It's healthier to be naked!

Our delegation, anonymous method, and Lambda expression evolution have ended. However, there seems to be another problem. If our anonymous method does not contain parameters, how should Lambda be written? Well, let alone the answer. Let me think about it. Is it true that "() => {execution statement }"? That's it!

I am a little annoyed when I first came into contact with this bt Lambda expression. The syntax is concise and concise, but after a long time, you will find that it is too powerful, you will love this bt Lambda expression.

 

 

From http://www.cnblogs.com/swjm119/archive/2011/12/10/2283271.html

Suppose we have a generic object list <t> and T is of the int type. We need to use this object method findall (predicate <t> match) to find the even number in the list, how do you implement it?

Description: predicate <t> is a generic delegate. Its prototype is public delegate bool predicate <t> (t obj). This delegate is used to input a T-type object, A boolean value is returned after logical judgment.

Delegate

The first thing you may think of is delegate implementation. The implementation method is as follows:

// Method 1
Static Void Method1 ()
{
// Create a list <int> Object
List < Int > List = New List < Int > ();
List. addrange ( New Int [] { 1 , 2 , 3 , 4 , 5 , 6 });

// define a DeleGate
predicate int callback = New predicate int (isevennumber );
// run the findall method, this method uses the incoming delegate callback to determine whether the integer in the list is an even number
List int evennumbers = List. findall (callback);

// Output
Foreach(IntIInEvennumbers)
{
Console. Write (" {0: 0} ", I );
}

Console. writeline ();
}

// Determines whether the input integer is an even number.
Static BoolIsevennumber (IntI)
{
ReturnI %2=0;
}Copy code

This method is good, simple, and intuitive. What are some of them? The Code seems cumbersome. We only need to execute a judgment statement like "I % 2 = 0", but we need to define a method and a delegate for this statement. If this method is not used elsewhere, is there any way to save it? (of course it is not really omitted. After compilation, this method actually exists, the purpose is at least not to let us enter a method and a delegate for this statement )? Now, our anonymous method is coming soon!

Anonymous Method

See the following code:

Static Void Method2 ()
{
// Create a list <int> Object
List < Int > List = New List < Int > ();
List. addrange ( New Int [] { 1 , 2 , 3 , 4 , 5 , 6 });

// Create an anonymous method and pass it to the findall method.
List <Int> Evennumbers = List. findall
(
Delegate(IntI)
{
ReturnI %2=0
;
}

);

// Output
Foreach(IntIInEvennumbers)
{
Console. Write (" {0: 0} ", I );
}

Console. writeline ();
}Copy code

In the above exampleDelegate(IntI ){ReturnI %2=0;} The statement creates an inline anonymous method delegate and passes it to findall to determine whether an integer in the list is an even number. Compared with Method1, we do not need to define a method and a delegate. The code is much reduced, but is it awkward? What is the prototype of this anonymous method?

A little analysis. (Int I) is the parameter list of the defined anonymous method. Return returns a Boolean value, which is the return value of the method. In this case, the delegate prototype of our inline anonymous method is:

Delegate bool anonymous (int I)

Looks familiar! This is not the same as the predicate <t> prototype Public Delegate bool predicate <t> (t obj). T is the same after it is substituted into the int type! Yeah, that's a coincidence! No, unfortunately not. If the prototype of the anonymous method you defined is not the same, the compiler will directly report an error! The list <int>. findall method requires a predicate <t> delegate!

Well, the delegate definition syntax of the inline anonymous method is like this:

Delegate (Parameter list)
{
Execution statement
} Copy code

Lambda expressions

The implementation of the anonymous method is concise enough. Is there any more concise syntax to implement it? What? Concise? The syntax of the anonymous method is almost dizzy. I need to use a concise method. Some BT! That's how Microsoft Works. Let's take a look at the more BT lambda expressions. The code above:

Static Void Method3 ()
{
// Create a list <int> Object
List < Int > List = New List < Int > ();
List. addrange ( New Int [] { 1 , 2 , 3 , 4 , 5 , 6 });

// Create a Lambda expression and pass it to the findall Method
List < Int > Evennumbers = List. findall
(
( IntX) => {ReturnX %2=0;} // Note: Oh, this is the well-known Lambda expression.
);

// Output
Foreach(IntIInEvennumbers)
{
Console. Write (" {0: 0} ", I );
}

Console. writeline ();
}Copy code

See this line of code: (int x) =>{ return X % 2 = 0 ;}

What is this? Lambda expressions? Right!

Let's analyze the syntax of lambda expressions: Ignore the "=>" symbol first. Lambda expressions are divided into two parts by the symbol. The first half of the symbol is the parameter list, and the second half is the execution statement. to simplify it, the following is the result:

Parameter List => execution statement

Familiar? Well, it seems like, probably, seems, yes, because, so it's a little familiar. By the way, isn't this structure just like an anonymous method? Let's look back at the syntax of the anonymous method:

Delegate (parameter list) {execution statement}

As you can see, lambda expressions are anonymous methods! The difference is that the parameter list and execution statement are separated by the "=>" symbol. In this case, the statement (int x) =>{ return X % 2 = 0;} is just a delegate that passes in an inline anonymous method for findall, the parameter list of this method is (int x), and a Boolean value is returned.

So far, is it worth celebrating? We seem to have started to understand this bt Lambda expression. Now we should call it xiao'er. I don't want to see this confusing code anymore. However, don't be happy first. Microsoft said again. This is not the most concise! What? Isn't it concise? So you can write a more concise look? Second, add the following code:

 

Static Void Method4 ()
{
// Create a list <int> Object
List < Int > List = New List < Int > ();
List. addrange ( New Int [] { 1 , 2 , 3 , 4 , 5 , 6 });

// Create a Lambda expression and pass it to the findall Method
List < Int > Evennumbers = List. findall
(
X => X %2=0 // Is there something speechless here?
);

// Output
Foreach(IntIInEvennumbers)
{
Console. Write (" {0: 0} ", I );
}

Console. writeline ();
}Copy code

 

? Look at this:

X => X % 2 = 0

This is the second time we see the lambda expression. Just remember the syntax of the lambda expression :(Parameter List => execution statement. X is the parameter list in this formula. Why is X not connected to any parameter type? Because the compiler knows that the prototype of the method to be passed in is bool predicate <int> (int obj), it automatically considers the type of parameter X as Int. Similarly, the compiler also knows that the return value of the method is Boolean, And the execution statement (X % 2 = 0) is a Boolean expression. Therefore, the compiler also thinks that we want to return this expression. Finally, the lambda expression is like the little ones whose clothes are stripped away. It is streaking in our code. Well, it's good. It's healthier to be naked!

Our delegation, anonymous method, and Lambda expression evolution have ended. However, there seems to be another problem. If our anonymous method does not contain parameters, how should Lambda be written? Well, let alone the answer. Let me think about it. Is it true that "() => {execution statement }"? That's it!

I am a little annoyed when I first came into contact with this bt Lambda expression. The syntax is concise and concise, but after a long time, you will find that it is too powerful, you will love this bt Lambda expression.

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.