Delegate, anonymous delegate, and lambda expressions

Source: Internet
Author: User

1. Delegate

In. in. net, the delegate is a bit similar to the function pointer in C/C ++, but unlike the pointer, the delegate is a safe type, let's take the difference between two numbers as an example to declare a member method first:

Public int comparetwovalue (int A, int B) {int c = A-B; return C ;}

Declare another delegate:

 
Public Delegate int delemethod (int A, int B );

Then, we can call the member method above through this delegate. Note that the parameter type and return type of the method must match the parameter type and return type of the delegate. In this example, both the member method and delegate input two int values and output an int value.

Public int show () {delemethod d1 = new delemethod (comparetwovalue); // first instantiate return D1 (5, 10); // then call}

 

 

2. Anonymous Delegation

This is also called the anonymous method. In fact, this is only a change in the syntax form. Because type matching is still required during compilation, for the show method above, I can use anonymous delegation to express

Public int show1 () {delemethod D2 = delegate (int A, int B) {int c = A-B; return C ;}; return D2 (5, 10 );}

It can be seen that the syntax is simple, so I personally think that anonymous delegation is of no substantial use in C #2.0, because it is truly useful when Lamda expressions are involved in 3.0.

3. Lambda expressions

Use the Lamda expression to write the following method:

Public int show2 () {func <int, Int, int> F = (a, B) =>{ return a-B ;}; return F (5, 10 );}

Lamda expressions are only a manifestation of anonymous delegation. We can intuitively see that the Lamda expression has the least amount of code in the three methods.

Delegate, anonymous delegate, and 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.