问题
when I run this code
Expression left = Expression.Constant(10, typeof(int));
Expression right = Expression.Constant(10,typeof(int));
var method10 = typeof(Expression).GetMethod("Equal", new[] { typeof(Expression), typeof(Expression) });
Expression exp = Expression.Call(method10,left,right);
var lambda = Expression.Lambda<Func<bool>>(exp);
var compiled = lambda.Compile().DynamicInvoke();
I get the below error
Additional information: Expression of type 'System.Int32'
cannot be used for parameter of type 'System.Linq.Expressions.Expression'
of method 'System.Linq.Expressions.BinaryExpression Equal(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression)'
回答1:
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
回答2:
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;
回答3:
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);
来源:https://stackoverflow.com/questions/29045951/call-equal-method-of-expression