【问题标题】:Stuck with BinaryExpression in C#卡在 C# 中的 BinaryExpression
【发布时间】:2009-06-16 09:33:35
【问题描述】:

我要实现

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 我要么得到真/假,但不能得到 Condition 应该返回的 LeftEx 或 RightEx。

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

彼得

【问题讨论】:

  • 别忘了,你可以随时使用反射器或 ildasm 来查看编译器为你生成的表达式树代码。

标签: c# expression-trees


【解决方案1】:

我想你只需要:

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));

【讨论】:

  • 我认为 Func 返回类型应该是 int (Func)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-15
  • 2011-10-13
相关资源
最近更新 更多