c# - 将 LambdaExpression 转换为带装箱返回值的类型化 Expression<Func<T, object>>

标签 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”。 我如何在我的表达式中使用装箱?

最佳答案

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;
        }
    }

关于c# - 将 LambdaExpression 转换为带装箱返回值的类型化 Expression<Func<T, object>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34896107/

相关文章:

c# - 无法将类型 'int' 隐式转换为 'string'

c# - 并行数据处理

c++ - 如何访问可变 lambda 函数参数

c# - 为什么 .NET 异常没有被 try/catch block 捕获?

c# - 忽略具有特定更改模式的 checkin 文件

c++17 如何编写 is_pointer_pointer 泛型 lambda?

lambda - 如何在 DrRacket Scheme 中使用 lambda

c# - 使用 Breeze 手动应用 OData 查询选项并仍然返回 InlineCount

c# - MDB协议(protocol)(多点总线)——C#串口通信

c# - 如何在 C# 中从 JSON 自动生成/创建 SQL 服务器表