调用表达式的相等方法 [英] 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)'
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)'
推荐答案
除非我缺少某些东西,否则您不需要反思:
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);
很显然,您可以手动调用int.Equals(int)
方法...
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);
,但请注意有一个细微的区别:Expression.Equal
将使用==
运算符,而其他代码将使用Equals
方法.
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);
或
ExpressionType type = (ExpressionType)Enum.Parse(typeof(ExpressionType), methodName);
var exp = Expression.MakeBinary(type, left, right);
使用Enum.Parse
这篇关于调用表达式的相等方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!