Sunday, August 14, 2011

Expression Tree Rewriting, Followup

After a short trip around Google, I came across ExpressionVisitor. With ExpressionVisitor, I am able to visit each expression in the tree with the ability to replace that expression with another if needed.

Here's an ExpressionVisitor I wrote that finds all uses of one expression and replaced those uses with another expression:

public class Modifier : ExpressionVisitor
{
    private Expression _oldValue;
    private Expression _newValue;
	
    public Modifier(Expression oldValue, Expression newValue)
    {
        _oldValue = oldValue;
        _newValue = newValue;
    }

    public override Expression Visit(Expression b)
    {
        if (b == _oldValue)
            return _newValue;
		
        return base.Visit(b);
    }
}

It's really just that simple.  Look at every branch; if the branch uses expression A, replace with B; otherwise, look deeper into the branch.

No comments:

Post a Comment