.NET StringBuilder 预先添加一行 [英] .NET StringBuilder preappend a line
问题描述
我知道 .NET 中的 System.Text.StringBuilder
有一个 AppendLine()
方法,但是,我需要在一个 StringBuilder
.我知道你可以使用 Insert()
来附加一个字符串,但我似乎不能用一行来做到这一点,我可以使用下一行字符吗?我正在使用 VB.NET,因此最好使用 VB.NET,但 C# 中的答案也可以.
I know that the System.Text.StringBuilder
in .NET has an AppendLine()
method, however, I need to pre-append a line to the beginning of a StringBuilder
. I know that you can use Insert()
to append a string, but I can't seem to do that with a line, is there a next line character I can use? I am using VB.NET, so answers in that are preferable, but answers in C# are ok as well.
推荐答案
有我可以使用的下一行字符吗?
is there a next line character I can use?
您可以使用 Environment.NewLine
获取为此环境定义的换行符.
Gets the newline string defined for this environment.
例如:
StringBuilder sb = new StringBuilder();
sb.AppendLine("bla bla bla..");
sb.Insert(0, Environment.NewLine);
或者更好的是,您可以为此编写一个简单的扩展方法:
Or even better you can write a simple extension method for that:
public static class MyExtensions
{
public static StringBuilder Prepend(this StringBuilder sb, string content)
{
return sb.Insert(0, content);
}
}
然后你可以这样使用它:
Then you can use it like this:
StringBuilder sb = new StringBuilder();
sb.AppendLine("bla bla bla..");
sb.Prepend(Environment.NewLine);
这篇关于.NET StringBuilder 预先添加一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!