【问题标题】:Convert a LambdaExpression to typed Expression<Func<T, object>> with boxing return values [duplicate]将 LambdaExpression 转换为具有装箱返回值的类型化 Expression<Func<T, object>>
【发布时间】:2016-01-20 09:26:11
【问题描述】:

我想构建以下表达式:

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”。 如何在我的表达式中使用拳击?

【问题讨论】:

  • Expression&lt;Func&lt;T, object&gt;&gt; retval = Expression.Lambda&lt;Func&lt;T, object&gt;&gt;(Expression.Convert(property, typeof(object)), parameter);

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


【解决方案1】:
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;
        }
    }

【讨论】:

    猜你喜欢
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多