gpt4 book ai didi

c# - 您如何保存对 NewExpression 的引用?

转载 作者:太空宇宙 更新时间:2023-11-03 19:14:40 26 4
gpt4 key购买 nike

我有这个代码:

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;
}

哪个长话短说将数据库行上的属性绑定(bind)到 <T> .问题是当我想使用/返回 dataTransferObject ,它每次都实例化一个新副本。如何在不重新创建对象的情况下只获取引用?

最佳答案

您只需将 NewExpression 分配给一个变量,然后使用该变量代替 NewExpression

var dataTransferObject = Expression.Variable(typeof(T), "dto");
var assignment = Expression.Assign(
dataTransferObject,
Expression.New(typeof(T).GetConstructor(Type.EmptyTypes)));

(将这些表达式添加到 BlockExpression)

关于c# - 您如何保存对 NewExpression 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17931350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com