How to escape braces (curly brackets) in a format string in .NET

后端 未结 10 2368
不思量自难忘°
不思量自难忘° 2020-11-22 02:44

How can brackets be escaped in using string.Format.

For example:

String val = \"1,2,3\"
String.Format(\" foo {{0}}\", val); 

10条回答
  •  被撕碎了的回忆
    2020-11-22 03:14

    Escaping curly brackets AND using string interpolation makes for an interesting challenge. You need to use quadruple brackets to escape the string interpolation parsing and string.format parsing.

    Escaping Brackets: String Interpolation $("") and String.Format

    string localVar = "dynamic";
    string templateString = $@"

    {0}

    this is my {localVar} template using a {{{{custom tag}}}}
    "; string result = string.Format(templateString, "String Interpolation"); // OUTPUT:

    String Interpolation

    this is my dynamic template using a {custom tag}

提交回复
热议问题