将{带入C#的逐字字符串

pro*_*eek 13 .net c# stringtemplate

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

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

using System;

class DoFile {

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

当我在逐字字符串中使用'{'或'}'时出现错误,我想这是因为'{'或'}'用于参数标记,例如{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 
Run Code Online (Sandbox Code Playgroud)

Qui*_*son 17

你只需要用双花括号逃脱..

{{}}分别..

像下面的东西

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

这是一个用于测试的格式字符串,里面有{literal bracket}


Jim*_*lla 8

你把两个像这样{{或者}}.