首页 > 解决方案 > c# StringBuilder 具有 Linq-ish 功能 IfElse 这可能吗?

问题描述

我正在写一个 AST(抽象语法树),不是以树的形式,而是为了正确格式化我的代码。类似于自定义语言的 Clang,我使用 StringBuilder 来实现效果......现在我必须执行以下操作:

        public string Visit(IfStatement ifStatement, int indent = 0)
        {
            var sb = new StringBuilder()
                .Append('\t', indent)
                .Append(Token.IfKeyword.ToString())
                .AppendBetween(ifStatement.Test.Accept(this), "(", ")").AppendLine()
                .Append(ifStatement.Consequent.Accept(this, indent + 1));

            if (ifStatement.Consequent != null)
            {
                sb.AppendLine()
                    .Append('\t', indent)
                    .AppendLine(Token.ElseKeyword.ToString())
                    .Append(ifStatement.Consequent.Accept(this, indent + 1));
            }

            return sb.ToString();
        }

这有时会变得非常复杂,所以我希望我可以做类似的事情:

sb.Append("Hello").IfElse(a > 5, sb => sb.Append("world!"), sb => sb.AppendLine("ME!!")).Append(...)

这可以使用类扩展来完成吗?非常感谢您的宝贵时间!

(顺便说一句,有没有更好的方法来写下 AST?我目前正在使用访问者模式来实现效果,但如果您知道更好的方法,请告诉我......如果某些线宽是,我还想引入文本换行达到..虽然不知道该怎么做)。

标签: c#stringbuilderclass-extensions

解决方案


我最终遵循了@GSerg 的建议。

public static StringBuilder IfElse(this StringBuilder sb, bool condition, Action<StringBuilder> if_true, Action<StringBuilder> if_false) 
{ 
    if (condition) { if_true(sb); } else { if_false(sb); } return sb; 
}

然后我可以这样做:

new StringBuilder().Append("World").IfElse(!IsNight(), sb => sb.Insert(0, "Hello ".AppendFormat(", my name is {0}", GetName())), sb => sb.Insert(0, "Bye "))

我只是不知道 lambda 是如何sb => sb.Whatever()工作的(我需要使用函数作为参数)。


推荐阅读