将LambdaExpression转换为类型化表达式<func <t,object =“”>&gt;与拳击返回值

时间:2016-01-20 09:26:11

标签: c# .net lambda boxing linq-expressions

我想构建以下表达式:

Expression<Func<T, object>>

我目前有以下代码:

public class Strategy<T>
{
    private static Expression<Func<T, object>> GetIt(PropertyInfo propertyInfo)
    {
        ParameterExpression parameter = Expression.Parameter(typeof(T));
        MemberExpression property = Expression.Property(parameter, propertyInfo);
        Type funcType = typeof(Func<,>).MakeGenericType(typeof(T), typeof(object));

        //next line fails: can't convert int to object
        LambdaExpression lambda = Expression.Lambda(funcType, property, parameter);

        Expression<Func<T, object>> retval = (Expression<Func<T, object>>)lambda;
        return retval;
    }
}

我的PropertyInfo对象的返回类型为“int”。 我怎样才能在我的表情中使用拳击?

1 个答案:

答案 0 :(得分:0)

public class ExpressionGetter<T>
    {
        public static Expression<Func<T, Object>> Get(PropertyInfo pInfo)
        {
            ParameterExpression parameter = Expression.Parameter(typeof(T));
            MemberExpression property = Expression.Property(parameter, pInfo);
            Type funcType = typeof(Func<,>).MakeGenericType(typeof(T), typeof(object));

            //next line fails: can't convert int to object

            LambdaExpression lambda;
            if (typeof (T).IsClass == false && typeof (T).IsInterface == false)
                lambda = Expression.Lambda(funcType, Expression.Convert(property, typeof (Object)), parameter);
            else
                lambda = Expression.Lambda(funcType, property, parameter);

            return (Expression<Func<T, object>>)lambda;
        }
    }