0

我在数据访问代码的上下文中使用下面的代码,在该代码中我从数据表项 (System.Data.DataRow) 动态创建业务对象。我希望能够将从数据行检索到的字节列分配给我的业务对象上的整数字段。

using System;
using System.Linq.Expressions;

namespace TestConsole {
    class Program {
        static void Main(string[] args) {
            var targetExp = Expression.Parameter(typeof(object), "target");
            var valueExp = Expression.Parameter(typeof(object), "value");
            var propertyExpression = Expression.Property(Expression.Convert(targetExp, typeof(SomeClass)), "SomeInt");
            var assignmentExpression = Expression.Assign(propertyExpression, Expression.Convert(valueExp, typeof(SomeClass).GetProperty("SomeInt").PropertyType));
            var compliedExpression = Expression.Lambda<Action<object, object>>(assignmentExpression, targetExp, valueExp).Compile();
            var obj = new SomeClass();
            byte ten = 10;
            compliedExpression.Invoke(obj, 10);
            compliedExpression.Invoke(obj, (int)10); //this works and i want to do this cast using expression trees, any idea?
            compliedExpression.Invoke(obj, ten); //Specified cast is not valid.
            Console.WriteLine(obj.SomeInt);
            Console.ReadKey();
        }
    }

    class SomeClass {
        public int SomeInt { get; set; }
    }

}
4

2 回答 2

1

您有一个装箱的byte,并试图将其拆箱为int. 那是无效的。

object obj = (byte)10;
int i = (int)obj; // InvalidCastException: Specified cast is not valid.

你可以做的是调用Convert.ToInt32 Method (Object)

int i = Convert.ToInt32(obj);
// i == 10

Convert.ChangeType 方法(对象,类型)

int i = (int)Convert.ChangeType(obj, typeof(int));
// i == 10
于 2013-09-13T03:30:35.293 回答
0

使用Expression.Convert我相信它会像演员一样工作

于 2013-09-13T05:00:04.697 回答