Created
September 8, 2014 22:51
-
-
Save AlexArchive/8016faac2bbb1c20ca25 to your computer and use it in GitHub Desktop.
Mutating Expression Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Program | |
{ | |
private static void Main() | |
{ | |
var operandOne = Expression.Parameter(typeof (int)); | |
var operandTwo = Expression.Parameter(typeof(int)); | |
var expression = | |
Expression.Lambda( | |
Expression.Add( | |
operandOne, | |
operandTwo | |
), | |
operandOne, | |
operandTwo | |
); | |
var visitor = new AddToSubtractExpressionVisitor(); | |
expression = (LambdaExpression)visitor.Visit(expression); | |
var func = expression.Compile() as Func<int, int, int>; | |
Console.WriteLine(func(10, 10)); | |
} | |
} | |
public class AddToSubtractExpressionVisitor : ExpressionVisitor | |
{ | |
protected override Expression VisitBinary(BinaryExpression node) | |
{ | |
return node.NodeType == ExpressionType.Add | |
? Expression.Subtract( | |
this.Visit(node.Left), this.Visit(node.Right)) | |
: node; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment