字符串 {0} 中的大括号
我经常在通常包含数字的字符串中看到大括号,例如:
string something = "I have {0} cats";
虽然我可以弄清楚这意味着什么,但我可以说我从未阅读过任何与其用法相关的文档。 C# 字符串文档似乎没有与这些相关的任何信息。有人能指出我正确的方向吗?
I often see curly braces in a string usually containing a number, such as:
string something = "I have {0} cats";
Whilst I can work out what this means, I can say I've never read any documentation relating to its useage. The c# string documentation seems to be void of any information relating to these. Can anyone point me in the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 string.Format 中用作值参数的占位符。 string.Format("我有 {0} 只猫", 5);打印“我有 5 只猫”
所以你可以使用 string.Format(something, 5);并得到与上面相同的结果
Used in string.Format as a place holder for a value parameter. string.Format("I have {0} cats", 5); prints "I have 5 cats"
So you could use string.Format(something, 5); and get the same result as above
这是
String.Format
,称为“复合格式”。有关详细信息,请查看此处。It's the normal format string used by
String.Format
, and is called "composite formatting". For more info about it, have a look here.*使用 C# 6.0 和朋友们,大括号不再只是用于
string.Format
了!现在它们可以表示插值字符串,您可以在其中混合 C# 对象和代码,而无需使用所有string.Format
&{0} {1} {2}
开销。注意:插值字符串以美元符号开头:
$
来自上面链接的语言参考页面:
注意: 如果您没有不知道,Console.WriteLine 有一种内置的 string.Format,如果您没有意识到在上面的示例中可能并不明显如果
您想在不依赖 Console.WriteLine 魔法的情况下获取相同的字符串,则可能更容易理解这...
...相当于...
* 正如@Ben 在上面的评论中指出的。 (抱歉,在路上错过了。)
*With C# 6.0 & friends, curly braces aren't just for
string.Format
any more! Now they can denote interpolated strings, where you can mix in C# objects and code without all thestring.Format
&{0} {1} {2}
overhead.NOTE: Interpolated strings start with a dollar sign:
$
From the language reference page linked above:
Note: If you didn't know,
Console.WriteLine
has a sort of built-instring.Format
, which might not be obvious in the above example if you didn't realize that going in.If you wanted to get the same string out without relying on Console.WriteLine magic, it might be easier to read that this...
... is equivalent to...
* As @Ben points out in a comment, above. (Sorry, missed that on the way in.)
几乎可以肯定它稍后会在
String.Format
调用中使用,其中编号占位符被附加参数替换:Its almost certainly later used in a
String.Format
call, where the numbered placeholders are replaced by additional parameters:查看 string.format:
http://msdn.microsoft.com/en-us /library/fht0f5be.aspx
Check out string.format:
http://msdn.microsoft.com/en-us/library/fht0f5be.aspx
检查 http://msdn.microsoft.com/ es-es/library/b1csw23d%28v=vs.80%29.aspx,它是string.format方法的文档,它是用于替换{0} 具有值。
Check http://msdn.microsoft.com/es-es/library/b1csw23d%28v=vs.80%29.aspx, its the documentation for the string.format method, it is the method used for replacing the {0} with a value.