编译表达树误会了吗?

Roy*_*mir 8 c# .net-4.0 expression-trees

我有这个表达式:

Expression<Func<string, bool>> f = s => s.Length < 5;
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

ParameterExpression p = Expression.Parameter (typeof (string), "s");
MemberExpression stringLength = Expression.Property (p, "Length");
ConstantExpression five = Expression.Constant (5);
BinaryExpression comparison = Expression.LessThan (stringLength, five);
Expression<Func<string, bool>> lambda= Expression.Lambda<Func<string, bool>> (comparison, p);
Run Code Online (Sandbox Code Playgroud)

// let:test

Func<string, bool> runnable = lambda.Compile();
Console.WriteLine (runnable ("kangaroo")); // False
Console.WriteLine (runnable ("dog")); //True
Run Code Online (Sandbox Code Playgroud)

我想问一下 .Compile()

什么编译?第一次执行与后期执行有什么区别......?

编译应该是一次发生的事情,而不是以后再发生....

什么/它对我有什么帮助?

Dar*_*rov 10

在运行时构建表达式树时,不会发出任何代码.这是一种在运行时表示.NET代码的方法.

一旦.Compile在表达式树上调用该方法,就会发出实际的IL代码,以将此表达式树转换为Func<string, bool>您可以在运行时调用的委托(在您的情况下).因此,表达式树表示的代码只有在编译后才能执行.

调用编译是一项昂贵的操作.基本上你应该调用它一次,然后缓存你​​可以用来多次调用代码的结果委托.