创建动态表达式来; Func键< T,Y>>

创建动态表达式来; Func键< T,Y>>

问题描述:

我想创建一个动态表达式来; Func键&LT; T,Y&GT;&GT; 。这里是一个适用于字符串但日期时间不工作的代码。通过不工作,我的意思是,我得到这个异常:

I want to create a dynamic Expression<Func<T,Y>>. Here is the code which works for string but doesn't work for DateTime. By doesn't work I mean, I get this exception:

'System.Nullable`1类型的表达式[System.DateTime的] 不能用于返回类型
'System.Object的'。

"Expression of type 'System.Nullable`1[System.DateTime]' cannot be used for return type 'System.Object'"

谁能分析错误

        Type type = typeof(DSVPNProjection);
        ParameterExpression arg = Expression.Parameter(type, "x");
        Expression expr = arg;

        PropertyInfo propertyInfo = type.GetProperty(sidx);
        expr = Expression.Property(expr, propertyInfo);

        var expression = 
        Expression.Lambda<Func<DSVPNProjection, object>>(expr, arg);



我是否需要修改对象来一些其他类型的?如果是,那么有哪些?正如你可以看到我想要动态获取的PropertyInfo和使用,作为Func键的第二个参数。

Do I need to change the object to some other type? If yes, then which? As you can see I am trying to dynamically fetch the PropertyInfo and use that as the 2nd parameter in Func.

有关值类型,你需要明确执行拳(即转换为对象):

For value types, you need to perform the boxing explicitly (i.e. convert to Object):

    Type type = typeof(DSVPNProjection);
    ParameterExpression arg = Expression.Parameter(type, "x");
    Expression expr = null;

    PropertyInfo propertyInfo = type.GetProperty(sidx);
    expr = Expression.Property(arg, propertyInfo);
    if (propertyInfo.PropertyType.IsValueType)
        expr = Expression.Convert(expr, typeof(object));

    var expression = 
    Expression.Lambda<Func<DSVPNProjection, object>>(expr, arg);