Home > Backend Development > C#.Net Tutorial > Take you to review C# delegates, anonymous methods, Lambda, generic delegates, expression tree code examples

Take you to review C# delegates, anonymous methods, Lambda, generic delegates, expression tree code examples

黄舟
Release: 2017-03-09 15:32:18
Original
1966 people have browsed it

Take you to review C# delegates, anonymous methods, Lambda, generic delegates, expression tree code examples:

These are commonplace things for the older generation of programmers, nothing new. It is full of charm for the new generation of programmers. In the past, many of the new generation had to go through a long process of study, understanding, and practice to master applications such as delegation and expression trees. Today I try to describe it in a simple way so that everyone can read this blog in five minutes.

The first minute: Commission

Some textbooks and blogs will mention events when talking about delegation. Although events are an instance of delegation, in order to make it easier to understand, today we will only talk about delegation and not events. First a piece of code:

The code below completes a demonstration of a delegated application. A commission consists of three steps:

public partial class WebForm3 : System.Web.UI.Page
{
    //step01:首先用delegate定义一个委托 。
    public delegate int CalculatorAdd(int x, int y);

    protected void Page_Load(object sender, EventArgs e)
    {
        //step03:用这个方法来实例化这个委托。
        CalculatorAdd cAdd = new CalculatorAdd(Add);
        //int result = cAdd(5, 6);
        int result = cAdd.Invoke(5,6);
    }
    // step02:声明一个方法来对应委托。
    public int Add(int x, int y)
    {
        return x + y;
    }
}
Copy after login

Step01: First define a delegate using delegate.

Step02: Declare a method to correspond to the delegate.

Step03: Use this method to instantiate this delegate.

At this point, a delegate should be completed, and the delegate can be called.

Second minute: Anonymous method

As you already know in the last minute, there are three steps to complete a commissioned application. You can’t do it without even one step. If you want to take a big step, be careful if you take a big step and it will hurt your eggs. But Microsoft is not afraid of pulling the strings, and insists on turning three steps into two! Therefore, Microsoft uses an anonymous method to simplify the above three steps. What do you say about anonymous methods? They are completely dispensable in C#. They are just the icing on the cake for C#. Some people ingeniously named them syntactic sugar.

public partial class WebForm3 : System.Web.UI.Page
{
    //step01:首先用delegate定义一个委托 
    public delegate int CalculatorAdd(int x, int y);

    protected void Page_Load(object sender, EventArgs e)
    {
        //step02:用这样的写法 delegate(int x, int y) { return x + y; },把一个方法赋值给委托
        CalculatorAdd cAdd = delegate(int x, int y) { return x + y; };
        int result = cAdd.Invoke(5, 6);
    }
}
Copy after login

Step01: First define a delegate using delegate.

Step02: Use this writing method delegate(int x, int y) { return x + y; } to assign a method to the delegate. In fact, this writing method is an anonymous method.

At this time, you will be surprised to find that this is not three steps in front of two steps?

Third minute: Lambda expression

With the addition of a few delegate keywords to an originally simple program, the code suddenly becomes abstruse, and fewer people understand abstruse things, so this can also be used as a bargaining chip for a salary increase. But Microsoft's design philosophy for C# is simplicity and ease of use. Microsoft tried every means to simplify the anonymous method delegate(int x, int y) { return x + y; }, and Lambda appeared. Let me look at several ways to write lambda expressions:

public partial class WebForm3 : System.Web.UI.Page
{
    public delegate int CalculatorAdd(int x, int y);

    protected void Page_Load(object sender, EventArgs e)
    {
        //方法一:
        CalculatorAdd cAdd1 = (int x, int y) => { return x + y; };
        int result1 = cAdd1(5, 6);

        //方法二:
        CalculatorAdd cAdd2 = (x, y) => { return x + y; };
        int result2 = cAdd2(5, 6);

        //方法三:
        CalculatorAdd cAdd3 = (x, y) => x + y;
        int result3 = cAdd2(5, 6);
    }
}
Copy after login

Method 1: Simply remove the delegate and add "=>" between () and {}.

Method 2: Based on method 1, eliminate all parameter types.

Method Three: If you want to do it, do it more thoroughly and remove {} and the return keyword.

You can write any of these methods, but it is just a nuisance for beginners. Sometimes they see this way of writing, and sometimes they see that way of writing, which makes people fascinated. If no one gives guidance, they will really be confused and difficult. That's the difficulty.

The fourth minute: Generic delegation

As the .net version is not upgraded, the new version must be different from the old version. Otherwise, how can Microsoft engineers report to their boss? So Microsoft is up to something new again.

public partial class WebForm3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //方法一:
        Func<int,int,int> cAdd1 = (int x, int y) => { return x + y; };
        int result1 = cAdd1(5, 6);

        //方法二:
        Func<int, int, int> cAdd2 = (x, y) => { return x + y; };
        int result2 = cAdd2(5, 6);

        //方法三:
        Func<int, int, int> cAdd3 = (x, y) => x + y;
        int result3 = cAdd2(5, 6);
    }
}
Copy after login

Whether it is an anonymous method or a Lambda expression, there are two steps to complete the application of a delegate. One is to define a delegate, and the other is to use a method to instantiate a delegate. Microsoft simply combined these two steps into one step. Use Func to simplify the definition of a delegate.

At this point, the application of a delegate can be completed with Func cAdd3 = (x, y) => x + y; where Func is the so-called generic delegate.

Fifth minute: Expression tree

In fact, the expression tree has nothing to do with delegation. If it must be related, let's just say that the expression tree is a container for storing delegation. If you have to talk more professionally, the expression tree is a data structure for accessing Lambda expressions. When using a Lambda expression, get it directly from the expression and use Compile() directly. The following code:

public partial class WebForm3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Expression<Func<int, int, int>> exp = (x, y) => x + y;
        Func<int, int, int> fun = exp.Compile();
        int result = fun(2, 3);
    }
}
Copy after login

What I touched on is very superficial, but at least it allowed everyone to review another article about delegation, anonymous methods, Lambda, generic delegation, and expression trees.


The above is the detailed content of Take you to review C# delegates, anonymous methods, Lambda, generic delegates, expression tree code examples. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template