c# - 生成 Expression.Assign 以设置小数点时出现异常?从十进制

标签 c# .net .net-core expression-trees

我在构建表达式时遇到了一个有趣的问题。我进行了一些基本的类型强制检查,以确保完成最少的转换,但是,我遇到了一个我没有预料到的问题。

当我尝试使用 Expression.Assign 生成 BinaryExpression 并且我要从 decimal 变为 decimal? 我收到异常:

System.ArgumentException: 'Expression of type 'System.Decimal' cannot be used for assignment to type 'System.Nullable'1[System.Decimal]

谁能解释一下?考虑以下评估为真:

typeof(decimal?).IsAssignableFrom(typeof(decimal))

预期的赋值应该等于下面的语句:

decimal? x = null;
decimal y = 10;
x = y;

有问题的代码:

private Expression BuildMapExpressionForValueMap(MemberInfo destinationProperty, MemberInfo sourceProperty)
{
    Expression assignmentExpression = Expression.PropertyOrField(_source, sourceProperty.Name);
    Type destinationType = destinationProperty.GetUnderlyingType();

    if (!destinationType.IsAssignableFrom(sourceProperty.GetUnderlyingType()))
    {
        assignmentExpression = BuildCastExpression(assignmentExpression, destinationType);
    }

    var expression = Expression.Assign(Expression.PropertyOrField(_destination, destinationProperty.Name)
                                     , assignmentExpression);


    return expression;
}

最佳答案

存在从不可空值类型到相应可空类型的隐式转换。您生成的表达式必须是显式的。与无法生成将 Int32 分配给 Int64 类型变量的表达式的原因相同。编译器显式生成转换调用,因此您不必这样做。尝试一下,您就会知道。

您必须添加转换。

var param = Expression.Variable(typeof(decimal?));
var value = Expression.Constant(20m, typeof(decimal));
var expr = Expression.Assign(param,
    //value // fails
    Expression.Convert(value, param.Type)
);

关于c# - 生成 Expression.Assign 以设置小数点时出现异常?从十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50935006/

相关文章:

c# - 如何使用控件(例如按钮)从表单调用事件?

c# - LINQ to SQL DataContext.Translate 和名称与源名称不同的属性

amazon-web-services - AWS Lambda(Linux 内核版本 – 4.4.51-40.60.amzn1.x86_64)在 Interop.Crypto.Pkcs12Parse 处抛出 MissingMethodException

c# - Entity Framework 在外键条件下产生左连接

c# - 是否可以将 SSRS 报告导出到 Excel,报告的图表是 Excel 图表而不是图像?

c# - 使用 accord.net 将数据分类为已知模式

c# - 保护网络服务

c# - 无法在静态上下文中访问非静态方法?

c# - 内容类型 - WebAPI - 请求 header

linux - Linux 上的 Chrome 中的 .NET Core 证书错误