调用 Equal 表达式的方法

call Equal method of Expression

当我运行这个代码

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

我收到以下错误

附加信息:类型 'System.Int32' 的表达式不能用于方法 'System.Linq.Expressions.BinaryExpression Equal(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression)'

类型 'System.Linq.Expressions.Expression' 的参数

尝试

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

而不是

var method10 = typeof(Expression).GetMethod("Equal", new[] { typeof(Expression), typeof(Expression) });
Expression exp = Expression.Call(method10,left,right);

你不需要反思,除非我遗漏了什么:

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

显然您可以手动调用 int.Equals(int) 方法...

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

但请注意有细微差别:Expression.Equal 将使用 == 运算符,而其他代码将使用 Equals 方法。

如果您真的想从字符串构建表达式:

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

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

使用 Enum.Parse

我解决了。谢谢大家

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;