繁体   English   中英

C#Null检查表达式树

[英]C# Null check in expression trees

我有一个名为User的类,其中有一个字段,用户可以在其中发送任何数据类型。 目前,我们正在发送int,double和string。

由于字段是动态的,因此字段名称可以是我们使用表达式树的任何名称。 我现在面临的问题是,如果选择查询中的字段为null或字段值,则抛出错误。

下面是我的代码:

Expression<Func<User, bool>> comparison = null;

if (Value.GetType() == typeof(int))
    comparison = EvaluateRules<int>(attributeName);
else if (Value.GetType() == typeof(double))
    comparison = EvaluateRules<double>(attributeName);
else if (Value.GetType() == typeof(string))
    comparison = EvaluateRules<string>(attributeName);


private Expression<Func<User, bool>> EvaluateRules<T>(string attributeName)
{
    var attributeParameter = Expression.Parameter(typeof(User), "user");
    Expression<Func<User, bool>> comparison = null;
    var parseMethod = typeof(T).GetMethod("Parse", new[] { typeof(string) });

    switch (policyOperator)
    {
        case Operator.GreaterThanOrEqual:
            if (Value.GetType() != typeof(string))
                comparison = Expression.Lambda<Func<User, bool>>(
                                    Expression.GreaterThanOrEqual(
                                        Expression.Call(parseMethod, Expression.Property(attributeParameter, attributeName)),
                                        Expression.Constant(Value)),
                                        attributeParameter);
            break;
    }

    return comparison;
}

resultUsers = from user in users.AsQueryable().Where(comparison) select user

有任何线索吗?

谢谢你的时间。

感谢您的回复。 我能够使用以下代码解决它。 张贴以防万一。

ParameterExpression attributeParameter = Expression.Parameter(typeof(User), "user");
MemberExpression attribute = Expression.Property(attributeParameter, attributeName);
BinaryExpression nullCheck = Expression.NotEqual(attribute, Expression.Constant(null, typeof(object)));
BinaryExpression condition = null;

 switch (policyOperator)
{
    case Operator.GreaterThanOrEqual:
    if (Value.GetType() != typeof(string))
        condition = Expression.GreaterThanOrEqual(Expression.Call(parseMethod, 
                        Expression.Property(attributeParameter, attributeName)), 
                            Expression.Constant(Value));

    .
    .
}

return Expression.Lambda<Func<User, bool>>(Expression.AndAlso(nullCheck, condition), attributeParameter);                           

暂无
暂无

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

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