Build expression trees to represent if

Deserializing of Expression tree using ExpressionSerialization on a full conditional expression ie ternary operator is giving error . If i am using ternary operator it causes FullConditionExpression (System Not Supported Exception)

Using code from following links:

http://archive.msdn.microsoft.com/exprserialization

Are there any latest version available for the above link?

http://metalinq.codeplex.com/

Tried this afterwards

public Expression<Func<object, string>> LabelCriteria { get; set; }

LabelCriteria = x =>
    {
      if (true)
          return "Cash";
      else      
          return " ";
    }

Expression doesn't support if - else block . It gives error as " A lambda expression with a statement body cannot be converted to expression tree . Is there any other way to do it.


你可以使用像这样的方法:

string myFunction(Object obj){
     //here your if-else...
}

LabelCriteria = x => myFunction(x);

You must use the conditional operator:

LabelCriteria = x => true ? "Cash" : " ";

It may be that the compiler is modifying the expression because of constant folding, however, since the condition is a constant expression ( true ). Try using a variable there and see what happens.


you could construct an expression tree explicitly with Expression API, refer to https://msdn.microsoft.com/en-us/library/bb397951.aspx

here's the code for your problem:

        ParameterExpression x = Expression.Parameter(typeof (object), "x");
        ConditionalExpression body = Expression.IfThenElse(
            Expression.Constant(true),
            Expression.Constant("Cash"),
            Expression.Constant(" ")
            );

        LabelCriteria = Expression.Lambda<Func<object, string>>(body, x);
链接地址: http://www.djcxy.com/p/84282.html

上一篇: C#中的三元运算符有没有简写?

下一篇: 构建表达式树来表示if