填充輸出
可以格式化字串以接受填充引數,該引數將指定插入的字串將使用的字元位置數:
${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.
右邊填充
右邊的填充(使用負填充值)將在當前值的末尾新增空格。
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 .
使用格式說明符填充
你還可以將現有格式說明符與填充結合使用。
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 ";
// ^^^^^