[Expression Tree] MSDN學習系列 2-修改運算式樹狀架構
Expression<Func<string, bool>> expr = name => name.Length > 10 && name.StartsWith("G");
若要修改運算式樹狀架構
public class AndAlsoModifier : ExpressionVisitor { public Expression Modify(Expression expression) { return Visit(expression); } protected override Expression VisitBinary(BinaryExpression node) { if (node.NodeType == ExpressionType.AndAlso) { Expression left = this.Visit(node.Left);//以遞迴方式繼續巡覽 Expression right = this.Visit(node.Right); return Expression.MakeBinary(ExpressionType.OrElse, left, right, node.IsLiftedToNull, node.Method); } return base.VisitBinary(node); } }
測試程式
static void Main(string[] args) { Expression<Func<string, bool>> expr = name => name.Length > 10 && name.StartsWith("G"); AndAlsoModifier treeModifier = new AndAlsoModifier(); Expression modifiedExpr = treeModifier.Modify(expr); Console.WriteLine("修改前:" + expr); Console.WriteLine("修改後:" + modifiedExpr); Console.Read(); }
參考來源
http://msdn.microsoft.com/zh-tw/library/bb546136.aspx原始程式
https://github.com/kimx/ExpressionLab