简体   繁体   English

空检查lambda表达式树

[英]Null check for lambda expression tree

How can I check if property of String type is null in order my following code to work and not fail during method calling ? 如何检查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;
    }
}

Add a null check to the resultant expression using AndAlso , like this: 使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM