关于c#:字符串{0}中的大括号

Curly braces in string {0}

我经常在通常包含数字的字符串中看到大括号,例如:

1
string something ="I have {0} cats";

虽然我能理解这意味着什么,但我可以说我从来没有读过任何关于它使用的文档。C字符串文档似乎没有与之相关的任何信息。有人能给我指出正确的方向吗?


在string.format中用作值参数的占位符。string.format("我有0 cats",5);打印"我有5个cats"

因此,您可以使用string.format(大约5);并获得与上面相同的结果


它是String.Format使用的普通格式字符串,称为"复合格式"。有关它的更多信息,请看这里。


*有了C 6.0&friends,大括号不再仅仅是用于String.Format!现在,它们可以表示内插字符串,您可以在其中混合C对象和代码,而不需要所有的String.Format&{0} {1} {2}开销。

注:插入字符串以美元符号开头:$

从上面链接的语言参考页:

Used to construct strings. An interpolated string looks like a
template string that contains interpolated expressions. An
interpolated string returns a string that replaces the interpolated
expressions that it contains with their string representations.

The arguments of an interpolated string are easier to understand than
a composite format string. For example, the interpolated string

Console.WriteLine($"Name = {name}, hours = {hours:hh}");

contains two interpolated expressions, '{name}' and '{hours:hh}'. The
equivalent composite format string is:

Console.WriteLine("Name = {0}, hours = {1:hh}", name, hours);

注:如果您不知道,Console.WriteLine有一种内置的String.Format,如果您没有意识到这一点,在上面的例子中可能并不明显。

如果您想在不依赖console.writeline magic的情况下得到相同的字符串,那么阅读这个…

1
string message = $"Name = {name}, hours = {hours:hh}"; // interpolated

…相当于…

1
string message = string.Format("Name = {0}, hours = {1:hh}", name, hours); // old school

The structure of an interpolated string is:

$" { [,] [<:format-string>] } ..."
where:

  • field-width is a signed integer that indicates the number of characters in the field. If it is positive, the field is right-aligned; if negative, left-aligned.
  • format-string is a format string appropriate for the type of object being formatted. For example, for a DateTime value, it could be a standard date and time format string such as"D" or"d".

You can use an interpolated string anywhere you can use a string
literal. The interpolated string is evaluated each time the code with
the interpolated string executes. This allows you to separate the
definition and evaluation of an interpolated string.

To include a curly brace ("{" or"}") in an interpolated string, use
two curly braces,"{{" or"}}".

*正如@ben在上面的评论中指出的那样。(对不起,在进去的路上没看到。)


几乎可以肯定的是,它后来用于String.Format调用,其中编号的占位符被其他参数替换:

1
2
3
string something ="I have {0} cats";
int myNumCats = 2
var theResult = String.Format(something,myNumCats);

签出字符串。格式:

http://msdn.microsoft.com/en-us/library/fht0f5be.aspx


检查http://msdn.microsoft.com/es/library/b1csw23d%28v=vs.80%29.aspx,它是string.format方法的文档,它是用值替换0_的方法。