在C#中遇到BinaryExpression

时间:2009-06-16 09:33:35

标签: c# expression-trees

我想实施

Expression<Func<int, int, int>> Max = (p1,p2) => p1 > p2 ? p1:p2;

作为表达式树并尝试

ParameterExpression LeftEx = Expression.Parameter(typeof(int), "p1");
ParameterExpression RightEx = Expression.Parameter(typeof(int), "p2");
BinaryExpression GroesserAls =  Expression.GreaterThan(LeftEx, RightEx);
ConditionalExpression Cond = BinaryExpression.Condition(GroesserAls, LeftEx, RightEx);
Expression main = Cond.Test;
Expression<Func<int, int, bool>> Lam = Expression.Lambda<Func<int, int, bool>>(main,
  new ParameterExpression[] { LeftEx, RightEx });
Console.WriteLine(Lam.Compile().Invoke(333, 1200));

使用Cond我得到true / false但不是条件应该返回的LeftEx或RightEx。

我在文档中找不到任何内容。

彼得

1 个答案:

答案 0 :(得分:8)

我认为你只需要:

Expression<Func<int, int, int>> Lam =
    Expression.Lambda<Func<int, int, int>>(Cond, // <=== HERE
        new ParameterExpression[] { LeftEx, RightEx });

编辑 - 顺便说一下 - var是你的朋友:

    var p1 = Expression.Parameter(typeof(int), "p1");
    var p2 = Expression.Parameter(typeof(int), "p2");
    var body = Expression.Condition(Expression.GreaterThan(p1, p2), p1, p2);
    var lambda = Expression.Lambda<Func<int, int, int>>(body, p1, p2);
    var func = lambda.Compile();
    Console.WriteLine(func(333,1200));
    Console.WriteLine(func(1200,333));