c# - 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?我目前正在使用访问者模式来实现效果,但如果您知道更好的方法,请告诉我......如果某些线宽是,我还想引入文本换行达到..虽然不知道该怎么做)。
解决方案
我最终遵循了@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()
工作的(我需要使用函数作为参数)。
推荐阅读
- laravel - 选择特定选项后的 Laravel sortby
- terraform - 启动模板名称已在使用错误
- python - 在 Python Web 服务中同时接收和处理大量数据
- java - 将身份验证凭据传递到 gradle.properties
- android - ActionBar 可见性的 Observable/LiveData?
- python - 用'x'替换列表中的重复值?
- android - 编辑文本不显示值
- javascript - 如何在 js 资产文件中使用 ruby?(未定义的方法“主体”)
- vue.js - Vue - 从另一个站点加载外部组件
- java - Java:如果内部方法抛出错误,外部方法不应该也抛出错误吗?