调用Equal表达方法

时间:2015-03-14 05:56:41

标签: c# lambda 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.Expression'的{​​{1}}类型的参数

3 个答案:

答案 0 :(得分:2)

你不需要反思,除非我遗漏了一些东西:

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

答案 1 :(得分:1)

我解决了。谢谢你们

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;

答案 2 :(得分:0)

尝试

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