C#Null檢查表達式樹

c# expression-trees

我有一個名為User的類,其中有一個字段,用戶可以發送任何數據類型。目前我們發送int,double和string。

由於該字段是動態的,因此字段名稱可以是我們使用表達式樹的任何內容。我現在面臨的問題是,如果select字段或字段值中的字段為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 with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow