将两个lambda与Expression相乘

时间:2016-12-07 15:42:43

标签: c# performance lambda linq-expressions

基本上我正在尝试将两个lambdas与Expression类相乘,但我甚至无法构建并且无法找到相关文档。这是我的代码:

var f = x=>x+2;
var g = x=>x+3;
var argX = Expression.Parameter(typeof(double), "x");
var fg = Expression.Multiply(Expression.Constant(g, typeof(Func<double, double>)), Expression.Constant(f, typeof(Func<double, double>)));
//var fg = Expression.Multiply(Expression.Constant(g),Expression.Constant(f));
var lambda = Expression.Lambda<Func<double, double>>(f3, argX);
return lambda.Compile();

2 个答案:

答案 0 :(得分:4)

你想要这样的东西:

-lxyz

如果我这样称呼它:

Expression<Func<double,double>> f = x => x + 2;
Expression<Func<double,double>> g = x => x + 3;

var param = Expression.Parameter(typeof(double));
var invokeF = Expression.Invoke(f, param);
var invokeG = Expression.Invoke(g, param);

var mult = Expression.Multiply(invokeF,invokeG);

var lambda = ((Expression<Func<double, double>>)Expression.Lambda(mult, param)).Compile();

我得到30作为有效答案。

答案 1 :(得分:0)

为此,只需将fg定义为Expression

var argX = Expression.Parameter(typeof(double), "x");

var f = Expression.Add(argX, Expression.Constant(3.0)); // applies to x => x + 3
var g = Expression.Add(argX, Expression.Constant(2.0)); // applies to x => x + 2
var fg = Expression.Multiply(f, g); // applies to f(x) * g(x)
var lambda = Expression.Lambda<Func<double, double>>(fg, argX);

现在这样称呼:

var r = lambda.Compile()(1);

返回12