填充输出

可以格式化字符串以接受填充参数,该参数将指定插入的字符串将使用的字符位置数:

${value, padding}

注意: 正填充值表示左填充,负填充值表示右填充。

左边填充

左边填充为 5(在数字值之前添加 3 个空格,因此在结果字符串中总共占用 5 个字符位置。)

var number = 42;
var str = $"The answer to life, the universe and everything is {number, 5}.";
//str is "The answer to life, the universe and everything is    42.";
//                                                           ^^^^^
System.Console.WriteLine(str);

输出:

The answer to life, the universe and everything is    42.

.NET 小提琴现场演示

右边填充

右边的填充(使用负填充值)将在当前值的末尾添加空格。

var number = 42;
var str = $"The answer to life, the universe and everything is ${number, -5}.";
//str is "The answer to life, the universe and everything is 42   .";
//                                                           ^^^^^
System.Console.WriteLine(str);

输出:

The answer to life, the universe and everything is 42   .

.NET 小提琴现场演示

使用格式说明符填充

你还可以将现有格式说明符与填充结合使用。

var number = 42;
var str = $"The answer to life, the universe and everything is ${number, 5:f1}";
//str is "The answer to life, the universe and everything is 42.1 ";
//                                                           ^^^^^

.NET 小提琴现场演示