简体   繁体   English

如何使用表达式树类型

[英]How To Use An Expression Tree Type

The MSDN documentation on Lamba Expressions provides an example of how to create an expression tree type but it does not show how to use it: 关于Lamba表达式的MSDN文档提供了有关如何创建表达式树类型的示例,但未显示如何使用它:

using System.Linq.Expressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<del> myET = x => x * x;
        }
    }
}

Can you complete this console application code so that it actually demonstrates the concept? 您能否完成此控制台应用程序代码,以使其实际演示该概念?

In general Expression Trees contain two parts. 通常,表达式树包含两个部分。 A set of parameters and a body. 一组参数和一个主体。 There is only one parameter shown in your example, which is x and the body uses that parameter by multiplying it by itself. 您的示例中仅显示一个参数,即x ,并且主体将其自身乘以该参数。

Essentially the behavior setup is something like this: 本质上,行为设置是这样的:

public int myET(int x)
{
    return x * x;
}

However, in order to access that behavior the value of the Expression must be accessed. 但是,为了访问该行为,必须访问Expression的值。 This value is a delegate, and is accessed through compiling the expression using .Compile() . 该值是一个委托,可以通过使用.Compile()编译表达式来访问。 Its type will be a Func with the type parameters of your del delegate which were returning int and accepting int . 它的类型将是一个带有del委托的类型参数的Func ,该参数将返回int并接受int

delegate int del(int i);
static void Main(string[] args)
{
    Expression<del> myET = x => x * x;
    del myFunc = myET.Compile();
}

Once compiled, the function may be called just like the method shown above with the behavior, where a value for the parameter is sent in, and the result of the code in the body is returned. 编译后,就可以像上面显示的方法一样调用该函数,其行为为:将参数的值发送进去,并返回主体中代码的结果。

delegate int del(int i);
static void Main(string[] args)
{
    Expression<del> myET = x => x * x;
    del myFunc = myET.Compile();
    int fiveSquared = myFunc(5);
    Console.WriteLine(fiveSquared);//25
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM