[英]How to use variable inside String.Format
I want to use String.Format
inside the loop, but it does not allowing me to define a variable i
inside the String.Format
. 我想在循环内使用
String.Format
,但是它不允许我在String.Format
内定义变量i
。 Here is my code 这是我的代码
StringBuilder Sb;
for(i=0 ;i<=myObj.length;i++)
{
Sb=Sb.Append(String.Format("{i,5}",myObj[i].Tostring()));
}
To use it in the Format
method, you use numbers corresponding to the indexes of the params array. 若要在
Format
方法中使用它,请使用与params数组的索引对应的数字。
Also, don't reassign Sb
, just call Append
or AppendFormat
: 另外,不要重新分配
Sb
,只需调用Append
或AppendFormat
:
Sb.Append(String.Format("{0,5}", myObj[i].ToString()));
//or
Sb.AppendFormat("{0,5}", myObj[i].ToString());
If you're fortunate enough to be on the latest and greatest C# version, you can skip Format
and do it with the new string interpolation syntax: 如果您很幸运能够使用最新最好的C#版本,则可以跳过
Format
并使用新的字符串插值语法进行操作:
Sp.Append($"{myObj[i],5}");
Or since all you're doing is padding, then you can also do: 或者由于您要做的只是填充,那么您还可以执行以下操作:
Sb.Append(myObj[i].ToString().PadLeft(5));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.