LambdaExpression 的嵌套调用是否存在错误?
我尝试编译并计算 LambdaExpression,如下所示:
加(10,加(1,2))
但结果是 4,而不是 13。
代码:
using System;
using System.Linq.Expressions;
namespace CheckLambdaExpressionBug
{
class Program
{
static void Main(string[] _args)
{
ParameterExpression p1 = Expression.Parameter(typeof (int), "p1");
ParameterExpression p2 = Expression.Parameter(typeof (int), "p2");
LambdaExpression lambda = Expression.Lambda(Expression.Call(typeof(Program).GetMethod("Plus"), p1, p2), p1, p2);
InvocationExpression exp1 = Expression.Invoke(
lambda,
Expression.Constant(1),
Expression.Constant(2)
);
InvocationExpression exp2 = Expression.Invoke(
lambda,
Expression.Constant(10),
exp1
);
var func = (Func<int>) Expression.Lambda(exp2).Compile();
int v = func();
Console.Out.WriteLine("Result = {0}", v);
}
public static int Plus(int a, int b)
{
return a + b;
}
}
}
I tried to compile and calculate LambdaExpression like:
Plus(10, Plus(1,2))
But result is 4, not 13.
Code:
using System;
using System.Linq.Expressions;
namespace CheckLambdaExpressionBug
{
class Program
{
static void Main(string[] _args)
{
ParameterExpression p1 = Expression.Parameter(typeof (int), "p1");
ParameterExpression p2 = Expression.Parameter(typeof (int), "p2");
LambdaExpression lambda = Expression.Lambda(Expression.Call(typeof(Program).GetMethod("Plus"), p1, p2), p1, p2);
InvocationExpression exp1 = Expression.Invoke(
lambda,
Expression.Constant(1),
Expression.Constant(2)
);
InvocationExpression exp2 = Expression.Invoke(
lambda,
Expression.Constant(10),
exp1
);
var func = (Func<int>) Expression.Lambda(exp2).Compile();
int v = func();
Console.Out.WriteLine("Result = {0}", v);
}
public static int Plus(int a, int b)
{
return a + b;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于似乎没有人发布此内容:
它看起来是 .NET 3.5 中的一个错误,并在 .NET 4 中修复。
Since nobody seems to be posting this:
It looks to be a bug in .NET 3.5, and is fixed in .NET 4.
而这似乎在 3.5 中也产生了 13:
whereas this seems to produce 13 in 3.5 too:
也许我需要将结果分配给本地变量
试试这个
var plus = new Func((a, b) => a + b);
var puls_1 = plus(1, 2);
var func = new Func(() => plus(10, plus_1));
var res = func();
Console.WriteLine(res);
maybe i needs to assign the result to a local var
try this
var plus = new Func((a, b) => a + b);
var puls_1 = plus(1, 2);
var func = new Func(() => plus(10, plus_1));
var res = func();
Console.WriteLine(res);