如何在模式有括号的 C# 中格式化字符串?当我运行以下语句时...
String.Format("Foo { Bar={0} }", this.Bar);
...我收到一个运行时异常:
System.FormatException:输入字符串的格式不正确。
我应该逃避括号吗?如何?
如何在模式有括号的 C# 中格式化字符串?当我运行以下语句时...
String.Format("Foo { Bar={0} }", this.Bar);
...我收到一个运行时异常:
System.FormatException:输入字符串的格式不正确。
我应该逃避括号吗?如何?
通过加倍括号来转义括号,例如{{
和}}
String.Format("Foo {{ Bar={0} }}", this.Bar);
尝试使用双花括号,它看起来像:
String.Format("Foo {{ Bar={0} }}", this.Bar);
看起来它已经被回答了:Escape curl.Format 中的花括号'{'
这种情况在 MSDN 上的文章Composite Formatting - Escaping Braces中进行了解释
左大括号和右大括号被解释为格式项的开始和结束。因此,您必须使用转义序列来显示文字左大括号或右大括号。在固定文本中指定两个左大括号(“{{”)以显示一个左大括号(“{”),或两个右大括号(“}}”)以显示一个右大括号(“}”)。
所以这应该是你的解决方案
String.Format("Foo {{ Bar={0} }}", this.Bar);