使用字符串值创建lambda表达式ConstantExpression

时间:2011-06-19 13:16:21

标签: c# lambda expression-trees constant-expression

我想创建lambda表达式,提供属性名称,值(作为字符串)和属性类型(作为Type)。

问题在于Expression.Constant(value1, propertyType);行 传递给Foo的value1是字符串。并且必须解析为“未知”类型

static Expression<Func<T, bool>> LabmdaExpression<T>(string property1, string value1, 
                                                     Type propertyType)
{                              
    var parameterExpression = Expression.Parameter(typeof(TheObject), "o");
    var memberExpression1 = Expression.PropertyOrField(parameterExpression, property1);

    //casting?
    var valueExpression1 = Expression.Constant(value1, propertyType);

    var binaryExpression1 = Expression.GreaterThan(memberExpression1, valueExpression1);
    return Expression.Lambda<Func<T, bool>>(binaryExpression1, parameterExpression);
}

1 个答案:

答案 0 :(得分:0)

我认为您应该T当前有TheObject

要转换字符串,可以在表达式中调用Convert.ChangeType()方法并转换生成的对象:

static readonly MethodInfo ChangeTypeMethod = typeof(Convert).GetMethod(
    "ChangeType", new[] { typeof(object), typeof(Type) });

static Expression<Func<T, bool>> LabmdaExpression<T>(
    string property1, string value1, Type propertyType)
{
    ParameterExpression parameterExpression = Expression.Parameter(typeof(T), "o");
    MemberExpression memberExpression1 = Expression.PropertyOrField(
        parameterExpression, property1);

    Expression convertedObject = Expression.Call(
        ChangeTypeMethod, Expression.Constant(value1),
        Expression.Constant(propertyType));
    Expression converted = Expression.Convert(convertedObject, propertyType);

    BinaryExpression binaryExpression1 = Expression.GreaterThan(
        memberExpression1, converted);
    return Expression.Lambda<Func<T, bool>>(binaryExpression1, parameterExpression);
}

只是强制转换不起作用,因为(int)"42"之类的代码无效。