C#delegate, anonymous method, Lambda, generic delegate, expression tree code example

C#delegate, anonymous method, Lambda, generic delegate, expression tree code example

In some textbooks, blogs will mention events when talking about entrustment. Although the event is an example of entrustment, in order to make it easier to understand, we will only talk about entrustment and not events today.

最后更新 9/18/2021 11:39 AM
QueryWord
预计阅读 5 分钟
分类
.NET
标签
.NET C# expression tree generic delegates anonymous method

First minute: commission

In some textbooks, blogs will mention events when talking about entrustment. Although the event is an example of entrustment, in order to make it easier to understand, we will only talk about entrustment and not events today. Let's start with a paragraph of code:

The code below completes a demonstration of a delegated application. An entrustment has three steps:

class Program
{
    //step01:首先用delegate定义一个委托 。
    public delegate int CalculatorAdd(int x, int y);

    static void Main(string[] args)
    {
        //step03:用这个方法来实例化这个委托。
        CalculatorAdd cAdd = new CalculatorAdd(Add);

        //int result = cAdd(5, 6);
        int result = cAdd.Invoke(5, 6);
    }

    // step02:声明一个方法来对应委托。
    public static int Add(int x, int y)
    {
        return x + y;
    }
}
  • step01:首先用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: Anonymity method

I already knew in the last minute that completing a delegated application is divided into three steps, and there is no missing step. If you want to take big steps, be careful to pull the egg if you take big steps. But Microsoft is not afraid of pulling the ball and insists on making three steps into two steps! So Microsoft used an anonymous method to simplify the above three steps. How to put it? It's completely unnecessary in C#. It's just a icing on the cake for C#. Someone ingenuously named it Grammar Sugar.

class Program
{
    //step01:首先用delegate定义一个委托 。
    public delegate int CalculatorAdd(int x, int y);

    static void Main(string[] args)
    {
        //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);
    }
}
  • Step01: First define a delegate with delegate.
  • Step02: Use this writing to delegate(int x, int y) { return x + y; } to assign a method to the delegate. In fact, this writing is an anonymous method.

At this time, I will be surprised to find that this is not just taking three steps in two steps?

Third minute: Lambda expression

原本很简单的程序,加上几个 delegate 关键字,这代码一下就变得深奥了,深奥的东西懂的人就变少了,所以这个还可以作为加薪的筹码。但是微软对 C#的设计理念是简单易用。微软就想方设法的来简化delegate(int x, int y) { return x + y; }这个匿名方法,Lambda 就出现了。下边我来看几种 lambda 表达式的写法:

class Program
{
    public delegate int CalculatorAdd(int x, int y);
    static void Main(string[] args)
    {
        //方法一:
        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);
    }
}

Fourth minute: Generic delegation

With the upgrade of the. NET version, the new version must be different from the old version. Otherwise, how can Microsoft engineers respond to their boss? So Microsoft is playing new tricks again.

class Program
{
    static void Main(string[] args)
    {
        //方法一:
        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);
    }
}

Whether it is an anonymous method or a Lambda expression, completing the application of a delegate cannot escape two steps. One step is to define a delegate, and the other step is to instantiate a delegate with a method. Microsoft simply combined these two steps into one step: using Func to simplify the definition of a delegation.

至此一个委托的应用就可用 Func<int, int, int> cAdd3 = (x, y) => x + y; 这样一句话来完成了,其中的 Func 就是所谓的泛型委托。

Fifth minute: Expression tree

In fact, the expression tree has nothing to do with delegates. If it has to be related, let's put it this way. The expression tree is a container for storing delegates. If I have to be more professional, an expression tree is a data structure that accesses Lambda expressions. When you want to use a Lambda expression, get it directly from the expression, and Compile() can be used directly, as follows:

class Program
{
    static void Main(string[] args)
    {
        Expression<Func<int, int, int>> exp = (x, y) => x + y;
        Func<int, int, int> fun = exp.Compile();
        int result = fun(2, 3);
    }
}
Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 4/22/2026

Support for. NET by operating system versions (250707 update)

Use virtual machines and test machines to test the support of each version of the operating system for. NET. After installing the operating system, it is passed by measuring the corresponding running time of the installation and being able to run the Stardust Agent.

继续阅读
同分类 / 同标签 2/7/2026

Summary of experience in using AOT

From the very beginning of project creation, you should develop a good habit of conducting AOT release testing in a timely manner whenever new features are added or newer syntax is used.

继续阅读