[英]How to convert Binding Expression left and right to lower?
I am using below code to generate dynamic binding expression; 我正在使用下面的代码来生成动态绑定表达式; here how to convert expression left and right part to lower? 这里如何将表达式的左右部分转换为较低的? because I wanted to filter either lower case and upper case filter. 因为我想过滤小写和大写过滤器。
private static Expression GetExpression<T>(ParameterExpression param, Filter filter)
{
MemberExpression member = Expression.Property(param, filter.PropertyName);
ConstantExpression constant = Expression.Constant(filter.Value);
switch (filter.Operation)
{
case Op.Equals:
return Expression.Equal(member, constant);
case Op.GreaterThan:
return Expression.GreaterThan(member, constant);
case Op.GreaterThanOrEqual:
return Expression.GreaterThanOrEqual(member, constant);
case Op.LessThan:
return Expression.LessThan(member, constant);
case Op.LessThanOrEqual:
return Expression.LessThanOrEqual(member, constant);
case Op.Contains:
return Expression.Call(member, containsMethod, constant);
case Op.StartsWith:
return Expression.Call(member, startsWithMethod, constant);
case Op.EndsWith:
return Expression.Call(member, endsWithMethod, constant);
}
return null;
}
If i understand you correctly then you can use the following: 如果我正确理解您的意思,那么您可以使用以下方法:
MemberExpression member = Expression.Property(param, filter.PropertyName);
ConstantExpression constant = Expression.Constant(filter.Value);
Expression left = Expression.Call(member, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));
Expression right = Expression.Call(constant, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));
In your switch replace member
with left
and constant
with right
在您的开关中,将member
替换为left
,将constant
替换为right
Update Regarding null checking 有关空检查的更新
You can check if the member property is null by this: (let's say that originalExpression
holds the expression from the switch
) 您可以通过以下方法检查member属性是否为空:(假设originalExpression
包含来自switch
的表达式)
var nullCheck = Expression.Equal(member, Expression.Constant(null, member.Type));
Expression.IfThenElse(nullCheck, Expression.Constant(false), originalExpression);
Expression.Conditional(nullCheck, Expression.Constant(false), originalExpression);
Update 2 更新2
You should check for null values both on the property and on the value: 您应该在属性和值上检查空值:
var nullCheckProp = Expression.Equal(member, Expression.Constant(null, member.Type));
var nullCheckVal = Expression.Equal(constant, Expression.Constant(null, constant.Type));
var nullCheckBoth = Expression.OrElse(nullCheckProp,nullCheckVal);
Expression.Conditional(nullCheckBoth, Expression.Constant(false), originalExpression);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.