C#内插字符串允许一个字符串添加左或右填充。根据您输出的内容,您可能需要调整填充水平。为什么C#在使用变量表示填充时存在问题? (请参见下面的示例。)
public static void example(string name, ApplicationCall NxRequest)
{
// Both 'headers' and 'values' are string arrays.
var headers = NxRequest.Headers();
var values = NxRequest.Values();
// I want to set the level of padding based on the maximum length
// in the 'headers' string array.
var padding = headers.Select(x => x.Length).Max();
const int constPadding = headers.Select(x => x.Length).Max();
for (int i = 0; i < headers.Length; i++)
{
// This works.
Console.WriteLine($"{headers[i].ToUpper().PadRight(padding)} {values[i]}");
// This doesn't work because constPadding cannot be set as a constant.
Console.WriteLine($"{headers[i].ToUpper(), constPadding} {values[i]}");
}
}
编辑:我介绍了一个更好的示例。
答案 0 :(得分:2)
您需要使pad为常数:
foreach (var item in new string[] { "cat", "dog", "mouse" })
{
const int pad = -12;
Console.WriteLine($"{item, pad}");
}
如果不能使用常量,则必须使用string padding函数,例如PadLeft或PadRight。