c# - 如何使用表达式树对数字类型应用隐式转换?

标签 c# dynamic expression-trees expandoobject

我有一个带有 int 字段的 ExpandoObject,我想使用表达式树将它转换为小数。

这是我正在使用的方法:

private static Expression<Func<dynamic, decimal>> CreateLambdaCastExpression()
    {
        // source
        var sourceParameterExpression = Expression.Parameter(typeof (object), "source");

        var binder = Binder.GetMember(
            CSharpBinderFlags.None, "IntProp", typeof (ExpressionTreeUtils),
            new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)});
        // source.sourceProperty
        var sourcePropertyExpression = Expression.Dynamic(
            binder, typeof (object), sourceParameterExpression);

        // (decimal) source;
        var castedValueExpression = Expression.Convert(sourcePropertyExpression, typeof (decimal));

        // () =>  (decimal) source;
        return Expression.Lambda<Func<dynamic, decimal>>(castedValueExpression,
            sourceParameterExpression);
    }

以这种方式调用它会导致 InvalidCastException:

        dynamic source = new ExpandoObject();
        source.IntProp = 1;

        decimal r = CreateLambdaCastExpression().Compile()(source);

如果我将 source.IntProp 设置为 1m,它会起作用(显然)

我读过msdn ExpressionConvert 仅对用户定义的类型执行隐式转换,所以这可能是解释。

知道如何对数字类型执行隐式转换吗?

最佳答案

更改这些行:

// CSharpBinderFlags.ConvertExplicit: explicit cast 
// (will convert double to decimal)
// CSharpBinderFlags.None: implicit cast
// (will convert int to decimal, won't convert double to decimal)
var convert = Binder.Convert(CSharpBinderFlags.ConvertExplicit, typeof(decimal), typeof(ExpressionTreeUtils));

// (decimal) source;
var castedValueExpression = Expression.Dynamic(
    convert, typeof(decimal), sourcePropertyExpression);

注意关于隐式/显式转换的注释。

(所以唯一改变的是 var castedValueExpression 的构建方式)

ideone有完整的例子。

关于c# - 如何使用表达式树对数字类型应用隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32024063/

相关文章:

c# - 下拉没有 id 也没有名字

asp.net-mvc - ASP MVC 3 : Dynamically resolve relative resources in views

c# - 从表达式树中获取 MethodInfo

c# - 是否有从表达式树或 CodeDOM 转换为 Reflection.Emit 的库?

c# - 使用表达式树动态构建 EF4 查询,NotSupportedException

c# - 异步非阻塞 IO 客户端如何工作?

c# - 具有泛型的结构图配置

c# - testdome.com 中的 TwoSum 和 BinarySearchTree;如何解决警告消息 : Performance test?

c# - 使用 AssemblyBuilder 构建资源程序集

c - 动态和静态混合分配