ValueTypes的动态表达式生成问题 [英] Dynamic Expression Generation Issues with ValueTypes

查看:156
本文介绍了ValueTypes的动态表达式生成问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立了一个框架,允许根据主排序列的列对表中的报表数据进行级联排序。它大部分工作,除了在一个特定但重要的情况下:当字段的属性是值类型时。我收到以下错误消息:

I built a framework that allows for cascaded sorting of report data in a table depending on what column is the master sorted column. It works for the most part, except in one specific, but important case: when the field's property is a value type. I receive the following error message:


System.ArgumentException:类型System.Int32的表达式不能用于返回类型System。对象'

System.ArgumentException: Expression of type 'System.Int32' cannot be used for return type 'System.Object'

我知道这意味着我需要打开ValueType的值,但是我并不完全确定如何这个特殊的情况。根据一些研究和这个SO答案我相信我需要使用 Expression.Convert 以某种方式。

I know that this means I need to box the value of the ValueType, but I'm not completely sure how to in this particular situation. Per some research and this SO answer I believe that I need to use Expression.Convert in some way.

我的代码是生成表达式。通用类型参数T是数据行的类型。 GetFullSortOrder()只返回一个字符串数组,表示类型T中列的名称(属性)也将被排序。

My code below is what generates the expressions. The generic type parameter T is the type of the "row" of data. The GetFullSortOrder() simply returns an array of strings that represent the names of the columns (properties) in the type T that will also be sorted.

public IEnumerable<Expression<Func<T, object>>> GetExpressions<T>(string sortedColumn) where T : IReportRecord
    {
        var columns = GetFullSortOrder(sortedColumn)
        var typeParameter = Expression.Parameter(typeof(T));
        foreach (var c in columns)
        {
            var propParameter = Expression.Property(typeParameter, c);
            yield return Expression.Lambda<Func<T, object>>(propParameter, typeParameter);
        }
    }

处理

The exception is thrown when processing Expression.Lambda<Func<T, object>>() when the Property selected in T is of a ValueType. What is needed to property box or return the correct value when the types aren't known until run-time?

推荐答案

你说,在运行时不知道类型是什么需要的属性框或返回正确的值?它 - 您需要使用 Expression.Convert ,并通过 typeof(object)。如果你想模拟C#编译器的工作,你应该只对值类型执行:

You said it - you need to use Expression.Convert and pass typeof(object). If you want to simulate what the C# compiler does, you should do it only for value types:

Expression result = propParameter;
if (typeof(T).IsValueType)
    result = Expression.Convert(result, typeof(object));
yield return Expression.Lambda<Func<T, object>>(result, typeParameter);

这篇关于ValueTypes的动态表达式生成问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆