c# – 对lambda表达式树进行空检查

前端之家收集整理的这篇文章主要介绍了c# – 对lambda表达式树进行空检查前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何检查String类型的属性是否为null以使我的以下代码工作并且在方法调用期间不会失败?
  1. if (SelectedOperator is StringOperators)
  2. {
  3. MethodInfo method;
  4.  
  5. var value = Expression.Constant(Value);
  6.  
  7. switch ((StringOperators)SelectedOperator)
  8. {
  9. case StringOperators.Is:
  10. condition = Expression.Equal(property,value);
  11. break;
  12.  
  13. case StringOperators.IsNot:
  14. condition = Expression.NotEqual(property,value);
  15. break;
  16.  
  17. case StringOperators.StartsWith:
  18. method = typeof(string).GetMethod("StartsWith",new[] { typeof(string) });
  19. condition = Expression.Call(property,method,value);
  20. break;
  21.  
  22. case StringOperators.Contains:
  23. method = typeof(string).GetMethod("Contains",value);
  24. break;
  25.  
  26. case StringOperators.EndsWith:
  27. method = typeof(string).GetMethod("EndsWith",value);
  28. break;
  29. }
  30. }

解决方法

使用 AndAlso向结果表达式添加空检查,如下所示:
  1. // Your switch stays as is
  2. switch ((StringOperators)SelectedOperator) {
  3. case StringOperators.Is:
  4. condition = Expression.Equal(property,value);
  5. break;
  6. ...
  7. }
  8. // Create null checker property != null
  9. var nullCheck = Expression.NotEqual(property,Expression.Constant(null,typeof(object)));
  10. // Add null checker in front of the condition using &&
  11. condition = Expression.AndAlso(nullCheck,condition);

猜你在找的C#相关文章