如何在. NET 中以格式字符串转义大括号(大括号)

如何使用string.Format逃脱括号。例如:

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

本示例不会引发异常,但是会输出字符串foo {0}

有没有办法逃脱括号?

答案

string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);
var inVal= "1, 2, 3";
var outVal= $" foo {{{value}}}";
//Output will be:  foo {1, 2, 3}
String val = "1,2,3";
String.Format(" foo {{{0}}}", val);
int i = 24;
string str = String.Format("{{{0:N}}}", i); //gives '{N}' instead of {24.00}
String.Format("{0}{1:N}{2}", "{", i, "}") //evaluates to {24.00}
string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);

您可以使用双开括号和双闭括号,它们只会在页面上显示一个括号。

string localVar = "dynamic";
string templateString = $@"<h2>{0}</h2><div>this is my {localVar} template using a {{{{custom tag}}}}</div>";
string result = string.Format(templateString, "String Interpolation");

// OUTPUT: <h2>String Interpolation</h2><div>this is my dynamic template using a {custom tag}</div>
var json = $@"{{""name"":""{name}""}}";
[TestMethod]
public void BraceEscapingTest()
{
    var result = String.Format("Foo {{0}}", "1,2,3");  //"1,2,3" is not parsed
    Assert.AreEqual("Foo {0}", result);

    result = String.Format("Foo {{{0}}}", "1,2,3");
    Assert.AreEqual("Foo {1,2,3}", result);

    result = String.Format("Foo {0} {{bar}}", "1,2,3");
    Assert.AreEqual("Foo 1,2,3 {bar}", result);

    result = String.Format("{{{0:N}}}", 24); //24 is not parsed, see @Guru Kara answer
    Assert.AreEqual("{N}", result);

    result = String.Format("{0}{1:N}{2}", "{", 24, "}");
    Assert.AreEqual("{24.00}", result);

    result = String.Format("{{{0}}}", 24.ToString("N"));
    Assert.AreEqual("{24.00}", result);
}
var value = "1, 2, 3";
var output = $" foo {{{value}}}";
var inVal= "1, 2, 3";
var outVal= $" foo {{{inVal}}}";
//Output will be:  foo {1, 2, 3}
string delimiter= "{{CR}}{{LF}}";