如何使用string.Format转义括号?

例如:

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

这个例子没有抛出异常,但是它输出字符串foo{0}。

有没有办法避开括号呢?


当前回答

转义括号:字符串插值$(""):

现在,你也可以像这样使用c#字符串插值(在c# 6.0中可用的特性):

var inVal = "1, 2, 3";
var outVal = $" foo {{{inVal}}}";
// The output will be:  foo {1, 2, 3}

其他回答

差不多了!大括号的转义序列是{{或}},因此对于您的示例,您将使用:

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>

您可以使用双左方括号和双右方括号,这将在您的页面上只显示一个方括号。

我的目标:

我需要将值“{CR}{LF}”分配给字符串变量分隔符。

c#代码:

string delimiter= "{{CR}}{{LF}}";

注意:要转义特殊字符,通常必须使用\。对于左花括号{,使用一个额外的,如{{。对于右花括号},使用一个额外的,}}。

我来这里是为了寻找如何在c#中构建JSON字符串(不序列化类/对象)。换句话说,如何在c#中使用插值字符串和“逐字字符串字面量”(双引号字符串加上“@”前缀)时转义大括号和引号,比如……

var json = $@"{{""name"":""{name}""}}";