Delegate, Lambda expression, event series 03, from delegate to Lamda expression, lambdalamda

Source: Internet
Author: User

Delegate, Lambda expression, event series 03, from delegate to Lamda expression, lambdalamda

In the article "delegate, Lambda expression, event series 02, and when to use delegate", the use of delegate makes the code much simpler.

namespace ConsoleApplication2
{
    internal delegate bool MyCalculateDelegate(int val);
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable<int> source = new List<int>(){2, 3, 4, 5, 6, 7, 8, 9,10, 11};
            MyCalculateDelegate del = LessThanFive;
            var result = GetNumbers(source, del);
            foreach (int n in result)
            {
                Console.WriteLine(n); 
            }
        }
        static IEnumerable<int> GetNumbers(IEnumerable<int> numbers, MyCalculateDelegate del)
        {
            foreach (int number in numbers)
            {
                if (del(number)) yield return number;
            }
        }
        static bool LessThanFive(int val)
        {
            return val < 5;
        }
        static bool LessThanTen(int val)
        {
            return val < 10;
        }
    }
}

 

However, the input parameters, output types, and implementation logic of the LessThanFive and LessThanTen methods are consistent. Is there a way to replace them? This is the time when Lambda expressions came into play! Lambda expressions are anonymous delegates separated by =>, input parameters on the left, and implementation process on the right.

 

namespace ConsoleApplication2
{
    internal delegate bool MyCalculateDelegate(int val);
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable<int> source = new List<int>(){2, 3, 4, 5, 6, 7, 8, 9,10, 11};
            var result = GetNumbers(source, n => n < 5);
            foreach (int n in result)
            {
                Console.WriteLine(n); 
            }
        }
        static IEnumerable<int> GetNumbers(IEnumerable<int> numbers, MyCalculateDelegate del)
        {
            foreach (int number in numbers)
            {
                if (del(number)) yield return number;
            }
        }
    }
}

As mentioned above, using Lambda expressions makes the code much simpler! The real parameter n => n <5 of GetNumbers is a Lambda expression that complies with the definition of the delegate MyCalculateDelegate. The input parameter is an integer and the output is a bool type.

 

Actually, lambda expression n => n <5 is a "syntactic sugar", and the following code is executed internally:

        ......
        MyCalculateDelegate del = LessThanFive;
        var result = GetNumbers(source, del);
        ......
        static bool LessThanFive(int val)
        {
            return val < 5;
        }


This can be seen from the IL level. Decompile with Reflector:

private static void Main(string[] args)
{
    List<int> <>g__initLocal0 = new List<int>();
    <>g__initLocal0.Add(2);
    <>g__initLocal0.Add(3);
    <>g__initLocal0.Add(4);
    <>g__initLocal0.Add(5);
    <>g__initLocal0.Add(6);
    <>g__initLocal0.Add(7);
    <>g__initLocal0.Add(8);
    <>g__initLocal0.Add(9);
    <>g__initLocal0.Add(10);
    <>g__initLocal0.Add(11);
    IEnumerable<int> source = <>g__initLocal0;
    IEnumerable<int> result = GetNumbers(source, (CS$<>9__CachedAnonymousMethodDelegate2 != null) ? CS$<>9__CachedAnonymousMethodDelegate2 : (CS$<>9__CachedAnonymousMethodDelegate2 = new MyCalculateDelegate(Program.<Main>b__1)));
    foreach (int n in result)
    {
        Console.WriteLine(n);
    }
}

 

As n => n> 5 complies with the definition of the delegate MyCalculateDelegate, a delegate of the MyCalculateDelegate type is created internally, then, the <Main> B _ 1 method generated by a compiler is assigned to the delegate variable.

 

[CompilerGenerated]
private static bool <Main>b__1(int n)
{
    return (n < 5);
}


<Main> the B _ 1 method is automatically generated by the compiler.

 

Conclusion: lambda expressions are actually "syntactic sugar". When the source code is compiled, the compiler will automatically generate a method that conforms to the delegate definition and then assign the method to the delegate.

 

 

"Delegation, Lambda expressions, and event series" include:

Delegate, Lambda expression, event series 01, Delegate, basic delegate usage, delegate Method and Target attribute delegate, Lambda expression, event series 02, when should I use delegate, Lambda expression, event series 03, from delegate to Lamda expression?


What is a lamda expression?

Msdn.microsoft.com/zh-cn/library/bb213687.aspx

Upgraded anonymous Delegation
Relatively strong

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 =>, which 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 expressions x => x * x are read as "x goes to x times x ". This expression can be assigned to the delegate type.

Lambda expressions are not understood. Here is a simple example,

The biggest function is to use anonymous functions and linq queries.
This is used on the anonymous method:
Delegate int del (int I );
Del myDelegate = x => x * x;
Int j = myDelegate (5); // j = 25
Equivalent
Delegate int del (int I );
Del myDelegate = delegate (int I) {I = I * I ;};
Int j = myDelegate (5); // j = 25
As for the future of linq, do not go into details.

Direct I + 1 ???
Haha, you have not encountered some situations that must be delegated.
For example, for cross-thread calls, you can only use delegates, while lambda expressions are a very convenient way of writing. This is purely for convenience.

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.