Reputation: 2814
I'm replacing a ParameterExpression with another with the following method:
public static Expression ReplaceParameter( this Expression expression,
ParameterExpression parameter, string name )
{
return new ExpressionParameterReplacer( parameter, name ).Visit( expression );
}
internal class ExpressionParameterReplacer : ExpressionVisitor
{
private readonly ParameterExpression _parameter;
private readonly string _name;
protected override Expression VisitParameter( ParameterExpression node )
{
if( node.Name == _name && (node.Type == _parameter.Type ||
node.Type.IsAssignableFrom( _parameter.Type )) )
{
return base.VisitParameter( _parameter );
}
return base.VisitParameter( node );
}
internal ExpressionParameterReplacer( ParameterExpression parameter, string name )
{
_parameter = parameter;
_name = name;
}
}
I'm using it like this:
ParameterExpression value = Expression.Parameter( ..., "value" );
return Expression.Block
(
new[] { value },
Expression.Assign( value, valueGetter ),
SomeLambdaExpression.Body.ReplaceParameter( value,
SomeLambdaExpression.Body.Parameters[0].Name);
)
As you see in order to replace the parameter at the moment I need to declare and assign a new, temporary, ParameterExpression.
I was wondering if there's a way to avoid that work and replace a ParameterExpression directly with the Expression providing the value (valueGetter
).
somethig like this to be clear:
return SomeLambdaExpression.Body.ReplaceParameter( valueGetter,
SomeLambdaExpression.Body.Parameters[0].Name);
Upvotes: 1
Views: 1187
Reputation: 244757
In your visitor, instead of return base.VisitParameter( _parameter );
, you can do just return _expression;
.
Upvotes: 1