在C#中格式化字符串

Rob*_*raż 3 c# formatexception

我正在尝试将数组元素格式化为一个表格,其中一些列具有正确的对齐方式,而另一些则如复合格式化文章中所示(或者C#插入字符串中的可选参数是什么?)

我为什么FormatException接听电话Console.WriteLine?

以下是演示此示例的示例:

using System;
namespace ConsoleApplication97
{
    class Program
    {
        public struct User
        {
            public string Name;
            public byte Age;
        }
        static void Main(string[] args)
        {
            User[] Bar = new User[2];
            Bar[0].Name = "Jan Kowalski";
            Bar[0].Age = 32;
            Bar[1].Name = "Piotr Nowak";
            Bar[1].Age = 56;
            for (int i = 0; i < Bar.Length; i++)
            {
                Console.WriteLine("{0 , -15} | { 1,  5}", Bar[i].Name, Bar[i].Age);
            }
            Console.ReadLine();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

值"名称"应位于左侧(对齐-15),"年龄"应位于右侧(对齐5).

D S*_*ley 9

有趣的是 - 格式化程序似乎对格式字符串中过多的空格感到挑剔.这对我有用:

Console.WriteLine("{0, -15} | {1, 5}", Bar[i].Name, Bar[i].Age);
Run Code Online (Sandbox Code Playgroud)