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

Mar 09, 2017 pm 03:32 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do lambda expressions handle exceptions in C++? How do lambda expressions handle exceptions in C++? Apr 17, 2024 pm 12:42 PM

In C++, there are two ways to handle exceptions using Lambda expressions: catch the exception using a try-catch block, and handle or rethrow the exception in the catch block. Using a wrapper function of type std::function, its try_emplace method can catch exceptions in Lambda expressions.

What is the meaning of closure in C++ lambda expression? What is the meaning of closure in C++ lambda expression? Apr 17, 2024 pm 06:15 PM

In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

What are the advantages of using C++ lambda expressions for multi-threaded programming? What are the advantages of using C++ lambda expressions for multi-threaded programming? Apr 17, 2024 pm 05:24 PM

The advantages of lambda expressions in C++ multi-threaded programming include simplicity, flexibility, ease of parameter passing, and parallelism. Practical case: Use lambda expressions to create multi-threads and print thread IDs in different threads, demonstrating the simplicity and ease of use of this method.

How to implement closure in C++ Lambda expression? How to implement closure in C++ Lambda expression? Jun 01, 2024 pm 05:50 PM

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

How does a C++ lambda expression capture external variables? How does a C++ lambda expression capture external variables? Apr 17, 2024 pm 04:39 PM

There are three ways to capture lambda expressions of external variables in C++: Capture by value: Create a copy of the variable. Capture by reference: Get a variable reference. Capture by value and reference simultaneously: Allows capturing of multiple variables, either by value or by reference.

C++ function call Lambda expression: callback optimization for parameter passing and return value C++ function call Lambda expression: callback optimization for parameter passing and return value May 03, 2024 pm 12:12 PM

In C++, you can use Lambda expressions as function parameters to achieve the flexibility of callback functions. Specifically: Parameter passing: wrap the Lambda expression through std::function and pass it to the function in the form of a function pointer. Return value processing: Specify the return value type when declaring the callback function pointer using std::function. Practical case: Optimize callbacks in GUI event processing, avoid creating unnecessary objects or function pointers, and improve code simplicity and maintainability.

How to perform lazy evaluation using C++ lambda expressions? How to perform lazy evaluation using C++ lambda expressions? Apr 17, 2024 pm 12:36 PM

How to perform lazy evaluation using C++ lambda expressions? Use lambda expressions to create lazily evaluated function objects. Delayed computation defers execution until needed. Calculate results only when needed, improving performance.

How to replace function pointer with C++ lambda expression? How to replace function pointer with C++ lambda expression? Apr 17, 2024 pm 04:24 PM

Replacing function pointers with lambda expressions improves readability, reduces boilerplate code, and increases reusability. Specifically, lambda expressions use the following syntax: [capturelist](parameterlist)->returntype{body}, and can be used in practical cases such as vector sorting to improve code simplicity and maintainability.

See all articles