您必须重建表达式才能添加字段。
假设这些表达式并不复杂并且basicUser
表达式将始终采用该形式,您可以更改表达式以添加新绑定。您可以在一个简单的访问者的帮助下做到这一点。
public class AddDobBindingVisitor : ExpressionVisitor
{
private ParameterExpression parameter;
protected override Expression VisitLambda<T>(Expression<T> node)
{
parameter = node.Parameters.Single();
return base.VisitLambda(node);
}
protected override Expression VisitMemberInit(MemberInitExpression node)
{
var member = typeof(User).GetProperty("DOB");
var newBindings = new[]
{
Expression.Bind(member, Expression.Property(parameter, "DOB")),
};
var updatedNode = node.Update(
node.NewExpression,
node.Bindings.Concat(newBindings));
return base.VisitMemberInit(updatedNode);
}
}
然后应用更改:
Expression<Func<Person, User>> basicUser = person => new User()
{
Name = person.FirstName
};
var detailedUser = (Expression<Func<Person, User>>)new AddDobBindingVisitor()
.Visit(basicUser);
// detailedUser:
// person => new User()
// {
// Name = person.FirstName,
// DOB = person.DOB
// }