C# 字符串中的大括号是什么意思? [英] What do the curly braces mean in C# strings?

查看:127
本文介绍了C# 字符串中的大括号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

while (rdr.Read())
{
    Console.WriteLine("Product: {0,-35} Total: {1,2}", rdr["ProductName"], rdr["Total"]);
}

这段代码中的 {0,-35} 是什么意思?

What does {0,-35} mean in this code?

推荐答案

更简单的一行是:

Console.WriteLine("{0}", 5);

该函数接受任意数量的参数.它们将被插入到相应索引处的字符串中.在这种情况下,索引零保存整数 5.结果是字符串5".

The function accepts any number of arguments. They will be inserted into the string at the corresponding index. In this case, index zero holds the integer 5. The result is the string "5".

现在,您可以选择指定格式字符串和索引.像这样:

Now, you have the option the specify a format string as well as an index. Like so:

Console.WriteLine("{0:0.00}", 5);

这将 5 格式化为 0.00,结果为 5.00.

This formats the 5 with 0.00, resulting in 5.00.

数字就是这种情况,但我认为这些更容易解释.对于字符串,格式"意味着对齐.另请注意,您使用逗号而不是冒号来分隔索引和格式.

Thats the case for numbers, but I think those are more easy to explain. For strings, the "format" implies alignment. Also note that you use a comma rather than a colon to separate index and format.

对齐(可选):这表示字符串的最小长度.值,字符串参数将右对齐,如果字符串不够长,字符串将用空格填充左边.值,字符串参数将左对齐如果字符串不够长,字符串将被填充右边的空格.如果未指定此值,我们将默认到字符串参数的长度.

alignment (optional): This represent the minimal length of the string. Postive values, the string argument will be right justified and if the string is not long enough, the string will be padded with spaces on the left. Negative values, the string argument will be left justied and if the string is not long enough, the string will be padded with spaces on the right. If this value was not specified, we will default to the length of the string argument.

所以在你的例子中:

  • {0,-35} 表示字符串必须至少为 35 个字符,左对齐(末尾有空格).
  • {1,2} 表示字符串必须至少为 2 个字符,右对齐(前面有空格填充).
  • {0,-35} means string has to be at least 35 characters, leftjustified (space padding on the end).
  • {1,2} means string has to be at least 2 characters, rightjustified (space padding in front).

我推荐这篇文章,因为以及 string.Format 文档.

这篇关于C# 字符串中的大括号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆