简体   繁体   English

StringBuilder.AppendFormat引发异常

[英]StringBuilder.AppendFormat Throws Exception

I have an instance of StringBuilder in my C# application wherein I would like certain lines to be padded with a varying number of spaces depending on the context. 我的C#应用​​程序中有一个StringBuilder实例,其中我希望根据上下文用不同数量的空格填充某些行。 My usage is very simple: 我的用法很简单:

StringBuilder MyStringBuilder = new StringBuilder();
MyStringBuilder.AppendFormat("{0:" + this._padding + "}"); // <-- Exception thrown here
MyStringBuilder.AppendLine("My data.");

If this._padding==10 , the resulting output should look something like this: 如果this._padding==10 ,则结果输出应如下所示:

  My data. 

How can I pad my strings without resorting to using a for loop? 如何在不使用for循环的情况下填充字符串? Thanks. 谢谢。

ADDITIONAL INFO 附加信息

Exception: "Index (zero based) must be greater than or equal to zero and less than the size of the argument list." 例外:“索引(从零开始)必须大于或等于零且小于参数列表的大小。”

  • You need to provide both the format and the arguments in one call. 您需要在一次调用中同时提供格式和参数。
  • To pad left you use {0,10} , not {0:10} . 要向左填充,请使用{0,10} ,而不要使用{0:10}

Try this: 尝试这个:

MyStringBuilder.AppendFormat("{0," + this._padding + "}", "My Data");

There is also a string.PadLeft method that you could use. 您还可以使用string.PadLeft方法。

MyStringBuilder.Append("My Data".PadLeft(this._padding));

您从未传递过供{0}引用的参数。

AppendFormat()希望将数据格式化为附加参数:

MyStringBuilder.AppendFormat("{0:" + this._padding + "}", "My data.");

这似乎是一种奇怪的方式:

sb.Append(' ', this._padding).AppendLine("My Data");

Try 尝试

//  AppendFormat("{0:" + this._padding + "}");
    AppendFormat("{0:" + this._padding + "}", "");

A place-holder is holding a place for something . 占位符正在为某事保留位置。

Exception: "Index (zero based) must be greater than or equal to zero and less than the size of the argument list." 例外:“索引(从零开始)必须大于或等于零且小于参数列表的大小。”

0 is greater than or equal to zero but it in this case it was not less than the size of the argument list ( 0 as well). 0大于或等于零,但在这种情况下,它不小于参数列表的大小(也为0 )。

You cannot simply write something like MyStringBuilder.AppendFormat("{0}"); 您不能简单地编写MyStringBuilder.AppendFormat("{0}");类的东西MyStringBuilder.AppendFormat("{0}"); You must give the variable to be formatted by the format string, like MyStringBuilder.AppendFormat("{0}", "My data"); 您必须给变量指定格式字符串的格式,例如MyStringBuilder.AppendFormat("{0}", "My data");

You can use IEnumerable.Repeat to generate arbitrary numbers of the same string/char. 您可以使用IEnumerable.Repeat生成相同字符串/字符的任意数字。

http://msdn.microsoft.com/en-us/library/bb348899.aspx http://msdn.microsoft.com/en-us/library/bb348899.aspx

A lame way of doing it, but should work 一种la脚的方式,但应该可以

for(int i=0; i <this._padding; i++)
{
   MyStringBuilder.AppendFormat("{0}"," ");
}

_padding needs to be an int _padding必须为int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM