Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

ParameterRebinder

By: a guest on May 5th, 2011  |  syntax: C#  |  size: 2.20 KB  |  views: 339  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. public class ParameterRebinder : ExpressionVisitor
  2. {
  3.     private ParameterExpression oldParameter;
  4.     private ParameterExpression newParameter;
  5.     protected ParameterRebinder(ParameterExpression oldParameter, ParameterExpression newParameter)
  6.     {
  7.         this.oldParameter = oldParameter;
  8.         this.newParameter = newParameter;
  9.     }
  10.     public Expression Rebind(Expression expr)
  11.     {
  12.         return Visit(expr);
  13.     }
  14.     public static Expression Rebind(Expression expr, ParameterExpression oldParameter, ParameterExpression newParameter)
  15.     {
  16.         return new ParameterRebinder(oldParameter, newParameter).Visit(expr);
  17.     }
  18.  
  19.     protected override Expression VisitParameter(ParameterExpression node)
  20.     {
  21.         return (node.Name == oldParameter.Name) ? newParameter : node;
  22.     }
  23.     protected override Expression VisitConstant(ConstantExpression node)
  24.     {
  25.         return base.VisitConstant(node);
  26.     }
  27.     protected override Expression VisitMember(MemberExpression node)
  28.     {
  29.         return node.Update(Visit(node.Expression));
  30.     }
  31.     protected override Expression VisitIndex(IndexExpression node)
  32.     {
  33.         return node.Update(Visit(node), Visit(node.Arguments));
  34.     }
  35.     protected override Expression VisitUnary(UnaryExpression node)
  36.     {
  37.         return node.Update(Visit(node.Operand));
  38.     }
  39.     protected override Expression VisitBinary(BinaryExpression node)
  40.     {
  41.         return node.Update(Visit(node.Left), node.Conversion, Visit(node.Right));
  42.     }
  43.     protected override Expression VisitConditional(ConditionalExpression node)
  44.     {
  45.         return node.Update(Visit(node.Test), Visit(node.IfTrue), Visit(node.IfFalse));
  46.     }
  47.     protected override Expression VisitMethodCall(MethodCallExpression node)
  48.     {
  49.         return node.Update(Visit(node.Object), Visit(node.Arguments));
  50.     }
  51.     protected override Expression VisitInvocation(InvocationExpression node)
  52.     {
  53.         return node.Update(Visit(node.Expression), Visit(node.Arguments));
  54.     }
  55.     protected override Expression VisitLambda<T>(Expression<T> node)
  56.     {
  57.         return node.Update(Visit(node.Body), node.Parameters.Select(param => (ParameterExpression)Visit(param)));
  58.     }
  59. }