开发者

C# Expression Tree Simple Arithmetic

I've been trying to figure out how to achieve some simple maths using the Expression class.

What I'm trying to do is this

(1 + 10 * 15)

When I try to do this via Expression.Add and Expression.Constant but the result I get is this

((1 + 10) * 15)

Which is not right as it evaluates the 1 + 10 first instead of 10 * 15.

Is there a way to combine Expression.Add/Multiply etc.. without it creating the brackets? I assume there is but I just can't find where or how!

The test code I have is this

        var v1 = Expression.Constant(1, typeof(int));
        var v2 = Expression.Constant(10, typeof(int));
        var v3 = Expression.Constant(15, typeof(int));

        var a1 = Expression.Add(v1, v2);
        var m2 = Expression.Multiply开发者_如何学运维(a1, v3);

Thanks for your time,

Richard.


var a1 = Expression.Multiply(v2, v3)
var m2 = Expression.Add(a1, v1)


You have to do your multiplication first:

Expression.Add(v1, Expression.Multiply(v2, v3))


Instead of

    var a1 = Expression.Add(v1, v2);
    var m2 = Expression.Multiply(a1, v3);

try with this

    var a1 = Expression.Multiply(v2, v3);
    var m2 = Expression.Add(v1, a1);


Here you find a bigger example: http://teusje.wordpress.com/2011/08/07/c-expression-trees/ It uses parameters, constants and binaryexpressions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜