What do the curly braces mean in C# strings?

后端 未结 5 1815
情书的邮戳
情书的邮戳 2021-02-14 22:40
while (rdr.Read())
{
    Console.WriteLine(\"Product: {0,-35} Total: {1,2}\", rdr[\"ProductName\"], rdr[\"Total\"]);
}

What does {0,-35} mean in this c

5条回答
  •  时光取名叫无心
    2021-02-14 23:19

    Strings like "Product: {0,-35} Total: {1,2}" are called composite format strings.

    The first numbers inside the curly braces (which start from zero) are called format items and correspond to the position of the arguments that come after the composite format string. These numbers can optionally be followed by a comma (,) and a minimum width to apply.

    The minimum width is useful for aligning columns. If the value is negative, the result will be left-aligned; otherwise, it will be right-aligned. For example:

    Console.WriteLine("Product: {0,-35} Total: {1,2}", "1stProduct", 99);
    Console.WriteLine("Product: {0,-35} Total: {1,2}", "SecondProduct", 111);
    

    Results in:

    Product: 1stProduct                          Total: 99
    Product: SecondProduct                       Total: 111  
    

    You can see that because we have specified a minimum width of 35 characters for the product names, they will always occupy at least that much space in the result string regardless of their actual length(which were 10 and 13 in the above example, respectively). And because we have specified -35(negative), product names will be left-aligned.

提交回复
热议问题