13

可能重复:
如何在.Net中转义格式字符串中的括号

如何在 C# 中逐字输入{}输入字符串?

using System;

class DoFile {

    static void Main(string[] args) {
        string templateString = @"
        \{{0}\}
        {1}
        {2}
        ";
        Console.WriteLine(templateString, "a", "b", "c");
    }
}

当我在逐字字符串中使用 '{' 或 '}' 时出现错误,我想这是因为 '{' 或 '}' 用于参数标记,例如{0}, {1}, {2}. \{不起作用。

Unhandled Exception: System.FormatException: Input string was not in a correct format.
  at System.String.ParseFormatSpecifier (System.String str, System.Int32& ptr, System.Int32& n, System.Int32& width, System.Boolean& left_align, System.String& format) [0x00000] in <filename unknown>:0 
  at System.String.FormatHelper (System.Text.StringBuilder result, IFormatProvider provider, System.String format, System.Object[] args) [0x00000] in <filename unknown>:0 
4

3 回答 3

16

你只需要用双花括号转义..

{{}}分别..

像下面的东西

string.Format("This is a format string for {0} with {{literal brackets}} inside", "test");

这是一个用于测试的格式字符串,其中包含 {literal 括号}

于 2011-05-13T19:37:41.900 回答
8

你放两个这样的{{or }}

于 2011-05-13T19:37:31.870 回答
0

{将and放在一个字符串中并没有什么特别之处},它们不应该被转义。此外,转义字符\在@分隔的字符串中无效。

要在方法中使用文字{}格式String.Format,请将它们加倍。因此,您的格式字符串将是:

string templateString = @"
    {{{0}}}
    {1}
    {2}
    ";
于 2011-05-13T19:43:01.613 回答