我已经为堆栈编写了一个程序。 ( https://stackoverflow.com/questions/2617367?tab=votes#tab-top ) 为此,我需要一个 StringBuilder 来向我展示堆栈中的内容,否则我将获得类名而不是内部的实际值。
我的问题是,除了 StringBuilder 之外,还有其他方法可以解决此类问题吗?
另外在其他什么情况下会发生这种问题?
另外,当我需要在 1 行上做几件事时,我编写 StringBuilder 的方式感觉很尴尬。
public override string ToString()
{
StringBuilder builder = new StringBuilder();
foreach (int value in tabel)
{
builder.Append(value);
builder.Append(" ");
}
if (tabel.Length == tabel.Length) // this is a bit messy, since I couldn't append after the rest above
{
builder.Append("(top:");
builder.Append(top);
builder.Append(")");
}
return builder.ToString();
}/*ToString*/
最佳答案
你可以使用 Array.ConvertAll和 String.Join而不是自己迭代列表。
此外,当您在一行中谈论多个事物时...您在任何地方都不会换行。
或者,如果您继续使用 StringBuilder,Append 方法会返回 StringBuilder,这样您就可以将调用链接在一起:
sb.Append("(top: ").Append(top).Append(")").AppendLine();
关于c# - StringBuilder 相关问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2617715/