我在数据访问代码的上下文中使用下面的代码,在该代码中我从数据表项 (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; }
}
}