zoukankan      html  css  js  c++  java
  • 修改Expression树

    最终这个问题还是在msdn上找到了解决方案

    http://msdn.microsoft.com/zh-cn/library/bb546136(v=vs.110).aspx

    1. using 指令(或 Visual Basic 中的 Imports 语句)添加到 System.Linq.Expressions 命名空间的文件中。
    2. public class AndAlsoModifier : ExpressionVisitor
      {
          public Expression Modify(Expression expression)
          {
              return Visit(expression);
          }
      
          protected override Expression VisitBinary(BinaryExpression b)
          {
              if (b.NodeType == ExpressionType.AndAlso)
              {
                  Expression left = this.Visit(b.Left);
                  Expression right = this.Visit(b.Right);
      
                  // Make this binary expression an OrElse operation instead of an AndAlso operation.
                  return Expression.MakeBinary(ExpressionType.OrElse, left, right, b.IsLiftedToNull, b.Method);
              }
      
              return base.VisitBinary(b);
          }
      }
      
      
      
    3. 将代码添加到 Program.cs(在 Visual Basic 为 Module1.vb)内的 Main 方法中,以便创建表达式树,并将其传递到要修改它的方法中。

      下面的代码创建一个包含条件 AND 运算的表达式。然后创建 AndAlsoModifier 类的实例,并将表达式传递到该类的 Modify 方法。将输出原始表达式树和修改过后的表达式树,以显示更改。

      using 指令(或 Visual Basic 中的 Imports 语句)添加到 System.Linq.Expressions 命名空间的文件中。

                  Expression<Func<string, bool>> expr = name => name.Length > 10 && name.StartsWith("G");
                  Console.WriteLine(expr);
      
                  AndAlsoModifier treeModifier = new AndAlsoModifier();
                  Expression modifiedExpr = treeModifier.Modify((Expression) expr);
      
                  Console.WriteLine(modifiedExpr);
      
                  /*  This code produces the following output:
      
                      name => ((name.Length > 10) && name.StartsWith("G"))
                      name => ((name.Length > 10) || name.StartsWith("G"))
                  */
      
      
      
      
    4. 编译并运行应用程序。

  • 相关阅读:
    word2013下,公式居中,编号右对齐
    Linux系统下,anaconda3与系统python共存
    LeetCode: 496 Next Greater Element I(easy)
    LeetCode: 463 Island Perimeter(easy)
    LeetCode: 620 Not Boring Movies(easy)
    C++: 其他类型转string
    LeetCode: 412 Fizz Buzz(easy)
    LeetCode: 344 Reverse String
    LeetCode: 566 Reshape the Matrix
    LeetCode: 575 Distribute Candies(easy)
  • 原文地址:https://www.cnblogs.com/swarb/p/9924372.html
Copyright © 2011-2022 走看看