call Equal method of Expression

前端 未结 3 901
萌比男神i
萌比男神i 2021-01-28 01:24

when I run this code

Expression left = Expression.Constant(10, typeof(int));
Expression right = Expression.Constant(10,typeof(int));

var method10 = typeof(Expr         


        
相关标签:
3条回答
  • 2021-01-28 02:09

    You don't need reflection, unless I'm missing something:

    Expression left = Expression.Constant(10, typeof(int));
    Expression right = Expression.Constant(10,typeof(int));
    Expression exp = Expression.Equal(left, right);
    var lambda = Expression.Lambda<Func<bool>>(exp);
    

    Clearly you could manually call the int.Equals(int) method...

    var method10 = left.Type.GetMethod("Equals", new[] { right.Type });
    Expression exp = Expression.Call(left, method10, right);
    var lambda = Expression.Lambda<Func<bool>>(exp);
    

    but note that there is a subtle difference: Expression.Equal will use the == operator, while the other code will use the Equals method.

    If you really want to build an expression from a string:

    string methodName = "Equal";
    MethodInfo method10 = typeof(Expression).GetMethod(methodName, new[] { typeof(Expression), typeof(Expression) });
    Expression exp = (Expression)method10.Invoke(null, new object[] { left, right });
    var lambda = Expression.Lambda<Func<bool>>(exp);
    

    or

    ExpressionType type = (ExpressionType)Enum.Parse(typeof(ExpressionType), methodName);
    var exp = Expression.MakeBinary(type, left, right);
    

    using the Enum.Parse

    0 讨论(0)
  • 2021-01-28 02:16

    I solved it . thanks guys

    Expression left = Expression.Constant(10, typeof(int));
    Expression right = Expression.Constant(10, typeof(int));
    ExpressionType expressionType;
    var tryParseRes = ExpressionType.TryParse("NotEqual", out expressionType);
    var exp = Expression.MakeBinary(expressionType, left, right);
    var lambda = Expression.Lambda<Func<bool>>(exp);
    var compiled = lambda.Compile().DynamicInvoke();
    if ((bool)compiled == false)
        areEventCondiotionsPassed = false;
    
    0 讨论(0)
  • 2021-01-28 02:30

    Try

    var exp = Expression.MakeBinary(ExpressionType.Equal, left, right);
    

    instead of

    var method10 = typeof(Expression).GetMethod("Equal", new[] { typeof(Expression), typeof(Expression) });
    Expression exp = Expression.Call(method10,left,right);
    
    0 讨论(0)
提交回复
热议问题