lambda 表达式树的空检查
Null check for lambda expression tree
如何检查 String 类型的 属性 是否为 null,以便我的以下代码能够正常工作并且在方法调用期间不会失败?
if (SelectedOperator is StringOperators)
{
MethodInfo method;
var value = Expression.Constant(Value);
switch ((StringOperators)SelectedOperator)
{
case StringOperators.Is:
condition = Expression.Equal(property, value);
break;
case StringOperators.IsNot:
condition = Expression.NotEqual(property, value);
break;
case StringOperators.StartsWith:
method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
condition = Expression.Call(property, method, value);
break;
case StringOperators.Contains:
method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
condition = Expression.Call(property, method, value);
break;
case StringOperators.EndsWith:
method = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
condition = Expression.Call(property, method, value);
break;
}
}
使用 AndAlso
向结果表达式添加空检查,如下所示:
// Your switch stays as is
switch ((StringOperators)SelectedOperator) {
case StringOperators.Is:
condition = Expression.Equal(property, value);
break;
...
}
// Create null checker property != null
var nullCheck = Expression.NotEqual(property, Expression.Constant(null, typeof(object)));
// Add null checker in front of the condition using &&
condition = Expression.AndAlso(nullCheck, condition);
如何检查 String 类型的 属性 是否为 null,以便我的以下代码能够正常工作并且在方法调用期间不会失败?
if (SelectedOperator is StringOperators)
{
MethodInfo method;
var value = Expression.Constant(Value);
switch ((StringOperators)SelectedOperator)
{
case StringOperators.Is:
condition = Expression.Equal(property, value);
break;
case StringOperators.IsNot:
condition = Expression.NotEqual(property, value);
break;
case StringOperators.StartsWith:
method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
condition = Expression.Call(property, method, value);
break;
case StringOperators.Contains:
method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
condition = Expression.Call(property, method, value);
break;
case StringOperators.EndsWith:
method = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
condition = Expression.Call(property, method, value);
break;
}
}
使用 AndAlso
向结果表达式添加空检查,如下所示:
// Your switch stays as is
switch ((StringOperators)SelectedOperator) {
case StringOperators.Is:
condition = Expression.Equal(property, value);
break;
...
}
// Create null checker property != null
var nullCheck = Expression.NotEqual(property, Expression.Constant(null, typeof(object)));
// Add null checker in front of the condition using &&
condition = Expression.AndAlso(nullCheck, condition);