当前我有一个StringBuilder
,其中有几行
StringBuilder foo = new StringBuilder()
.AppendLine("- one")
.AppendLine("- two")
.AppendLine("- three");
,我想为每个新行设置"- "
字符。伪代码:
StringBuilder foo = new StringBuilder()
.SetNewLineInitialCharacter("- ")
.AppendLine("one")
.AppendLine("two")
.AppendLine("three");
我不认为Insert
或Replace
是我要寻找的方法。我知道循环可以解决问题,但没有必要,我只是问是否有一种方法可以一次设置"- "
。
答案 0 :(得分:5)
许多方法之一是将StringBuilder包装在单独的类中。
void Main()
{
var sb = new StringBuilder();
var foo = new MyStringBuilder(sb, "- ")
.AppendLine("one")
.AppendLine("two")
.AppendLine("three");
var result = sb.ToString();
}
public class MyStringBuilder
{
private StringBuilder _sb;
private string _linePrefix;
public MyStringBuilder(StringBuilder sb, string linePrefix)
{
_sb = sb;
_linePrefix = linePrefix;
}
public MyStringBuilder AppendLine(string line)
{
_sb.Append(_linePrefix);
_sb.AppendLine(line);
return this;
}
public override string ToString()
{
return _sb.ToString();
}
}
答案 1 :(得分:4)
您可以使用包装好的StringBuilder进行此操作:
public class StringBuilderWrapper
{
private readonly string _prefix;
private readonly StringBuilder _builder;
public StringBuilderWrapper(StringBuilder builder, string prefix)
{
_prefix = prefix;
_builder = builder;
}
public StringBuilderWrapper AppendLine(string line)
{
_builder.Append(_prefix);
_builder.AppendLine(line);
return this;
}
public override string ToString()
{
return _builder.ToString();
}
}
为了方便起见,您可以从扩展方法中返回:
public static class StringBuilderExtensions
{
public static StringBuilderWrapper SetNewLineInitialCharacter(this StringBuilder builder, string prefix)
{
return new StringBuilderWrapper(builder, prefix);
}
}
然后这样称呼它:
var output = new StringBuilder()
.SetNewLineInitialCharacter("- ")
.AppendLine("one")
.AppendLine("two")
.AppendLine("three");
var outputString = output.ToString();
哪个输出:
- one
- two
- three
没有扩展方法,您可以这样称呼它:
var output = new StringBuilderWrapper(new StringBuilder(), "- ")
.AppendLine("one")
.AppendLine("two")
.AppendLine("three");
答案 2 :(得分:2)
一个简单的解决方案可能就是这样
public class CustomStringBuilder
{
private StringBuilder _builder;
private string _prefix;
public CustomStringBuilder (StringBuilder builder, string prefix)
{
_builder = builder;
_prefix = prefix;
}
public CustomStringBuilder CustomAppendLine(string text)
{
_builder .Append(_prefix);
_builder .AppendLine(text);
return this;
}
public override string ToString()
{
return _builder.ToString();
}
}
您可以这样称呼它:
CustomStringBuilderfoo = new CustomStringBuilder(new StringBuilder(), "- ")
.CustomAppendLine ("one")
.CustomAppendLine ("two")
.CustomAppendLine ("three");