How do I infer the usage of parentheses when translating an expression tree?

后端 未结 2 1129
我寻月下人不归
我寻月下人不归 2021-02-15 12:25

I am working on translating an expression tree to a format that resembles infix notation; I am not evaluating the tree or executing its operations. The tree contains both logic

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-15 12:52

    Try something like this, assuming that node.NodeType is of type NodeType, and that function Precedes exists and returns true if first parameter precedes the second.

    protected override Expression Visit(BinaryExpression node, NodeType parentType)
    {
        bool useParenthesis = Precedes(parentType, node.NodeType);
    
        if (useParenthesis)
            Console.Write("(");
    
        Visit(node.Left, node.NodeType);
        Console.WriteLine(node.NodeType.ToString());
        Visit(node.Right, node.NodeType);
    
        if (useParenthesis)
            Console.Write(")");
    
        return node;
    }
    

提交回复
热议问题