我有这个代码:
public static Func<IDataReader, T> CreateBinder<T>() {
NewExpression dataTransferObject = Expression.New(typeof(T).GetConstructor(Type.EmptyTypes));
ParameterExpression dataReader = Expression.Parameter(typeof(IDataReader), "reader");
IEnumerable<Expression> columnAssignments = typeof(T).GetProperties().Select(property => {
MethodCallExpression columnData = Expression.Call(dataReader, dataReaderIndexer, new[] { Expression.Constant(property.Name) });
MethodCallExpression setter = Expression.Call(dataTransferObject, property.SetMethod, new[] { Expression.Convert( columnData, property.PropertyType ) });
return setter;
});
columnAssignments = columnAssignments.Concat(new Expression[] { dataTransferObject });
BlockExpression assignmentBlock = Expression.Block(columnAssignments);
Func<IDataReader, T> binder = Expression.Lambda<Func<IDataReader, T>>(assignmentBlock, new[] { dataReader }).Compile();
return binder;
}
长话短说将数据库行上的属性绑定到<T>
. 问题是当我想使用/返回时dataTransferObject
,它每次都实例化一个新副本。如何在不重新创建对象的情况下获取参考?