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

前端之家收集整理的这篇文章主要介绍了c# – 对lambda表达式树进行空检查前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何检查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",value);
            break;

        case StringOperators.EndsWith:
            method = typeof(string).GetMethod("EndsWith",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);
原文链接:https://www.f2er.com/csharp/98194.html

猜你在找的C#相关文章