简体   繁体   English

C#中双引号中的String.Format

[英]String.Format in Double Quotes in C#

Is anybody can help me with string.Format for below line. 有人可以用string.Format帮我下线。 In '2056' I need to pass as {0}. 在“ 2056”中,我需要通过{0}。

string body = @"{""idTimeSerie"":""2056"",""idTso"":-1}";

Due to double quotes I can't get it to execute. 由于双引号,我无法执行它。

I've tried in this way but no success. 我已经尝试过这种方法,但没有成功。

string body = string.Format
                    (@"{""idTimeSerie"": "" \"{0}\" "",""idTso"":-1}", countryID);

you have to escape the curly braces 你必须逃避花括号

replace { to {{ 将{替换为{{

string body = @"{{""idTimeSerie"":""2056"",""idTso"":-1}}";

Edit : From MSDN - Another way of Escaping 编辑: 从MSDN - 另一种逃避方式

Opening and closing braces are interpreted as starting and ending a format item. 左括号和右括号被解释为格式项的开始和结束。 Consequently, you must use an escape sequence to display a literal opening brace or closing brace. 因此,您必须使用转义序列来显示文字左括号或右括号。 Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}"). 在固定文本中指定两个开括号(“{{”)以显示一个左括号(“{”)或两个右括号(“}}”)以显示一个右括号(“}”)。 Braces in a format item are interpreted sequentially in the order they are encountered. 格式项中的大括号将按其遇到的顺序顺序进行解释。 Interpreting nested braces is not supported. 不支持解释嵌套括号。

int value = 6324;
string output = string.Format("{0}{1:D}{2}", 
                             "{", value, "}");
Console.WriteLine(output);
// The example displays the following output: 
//       {6324}

Try this: 尝试这个:

string body = string.Format(@"{{ ""idTimeSerie"": ""{0}"", ""idTso"": -1 ", countryID) + "}";

Explanation: 说明:

1) When using the @ flavor of string literals, double quotes are indicated by "" (two consecutive double quotes). 1)当使用@ flavor的字符串文字时,双引号用""表示(两个连续的双引号)。

See MSDN: 请参阅MSDN:

@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.

2) Use {{ and }} to indicate a literal { and } respectively in your string format. 2)使用{{}} }分别以字符串格式表示文字{}

See MSDN (Escaping Braces): 请参阅MSDN(转义括号):

Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}"). 在固定文本中指定两个开括号(“{{”)以显示一个左括号(“{”)或两个右括号(“}}”)以显示一个右括号(“}”)。

你可以这样做:

string body = string.Format("{{\"idTimeSerie\":\"{0}\",\"idTso\":-1}}", countryID);

Don't use a verbatim string in this case. 在这种情况下,请勿使用逐字字符串。 I suspect you want: 我怀疑你想要:

string body = string.Format("{\"idTimeSerie\":\"{0}\",\"idTso\":-1}", countryID);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM