构建一个Expression来检查对象的两个属性是否相等?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了构建一个Expression来检查对象的两个属性是否相等?相关的知识,希望对你有一定的参考价值。
我试图理解Expression
s是如何工作的,所以我想象一个方法,它接受一个具有两个int
属性的对象,并返回布尔值表示它们是否相等,如下所示:
bool AreEqual(Foo foo)
{
return foo.Value1 == foo.Value2;
}
这是我建立的表达:
//build the parameter expression of the object
ParameterExpression parameter = Expression.Parameter(typeof(Foo), "x");
//the left member
MemberExpression leftMember = Expression.Property(parameter, "Value1");
//the right member
MemberExpression rightMember = Expression.Property(parameter, "Value2");
//the left lambda
LambdaExpression leftLmbda = Expression.Lambda(leftMember, parameter);
//the right lambda
LambdaExpression rightLambda = Expression.Lambda(rightMember, parameter);
//and here I evaluate the boolean expression:
Expression equalExpression = Expression.Equal(rightLambda, leftLmbda);
//the lambda of the equal expression
LambdaExpression lambda = Expression.Lambda(equalExpression, parameter);
//the object:
Foo foo = new Foo { Value1= 5, Value2=5 };
Delegate expression = lambda.Compile();
var eq = expression.DynamicInvoke(foo);
但它总是评估为false
。
我的猜测是我只构建一个lambda,但不知道如何在一个lambda中处理这两个属性
答案
Expression.Equal语句应该比较两个成员表达式。
//build the parameter expression of the object
ParameterExpression parameter = Expression.Parameter(typeof(Foo), "x");
//the left member
MemberExpression leftMember = Expression.Property(parameter, "Value1");
//the right member
MemberExpression rightMember = Expression.Property(parameter, "Value2");
//and here I evaluate the boolean expression:
Expression equalExpression = Expression.Equal(leftMember, rightMember);
//the lambda of the equal expression
LambdaExpression lambda = Expression.Lambda(equalExpression, parameter);
//the object:
Foo foo = new Foo { Value1 = 5, Value2 = 5 };
Delegate expression = lambda.Compile();
var eq = expression.DynamicInvoke(foo);
以上是关于构建一个Expression来检查对象的两个属性是否相等?的主要内容,如果未能解决你的问题,请参考以下文章