c#中的双引号不允许多行
Double quotes in c# doesn't allow multiline
例如
string str = "{\"aps\":{\"alert\":\"" + title + "" + message + "\"}}";
我需要把它写成可读性:
string str = "
{
\"aps\":
{
\"alert\":\"" + title + "" + message + "\"
}
}";
如何实现,请指教。
您可以使用 X-Tech 所说的,在每一行使用额外的连接运算符 ('+'),或使用符号 '@':
string str = @"
{
'aps':
{
'alert':'" + title + "" + message + @"'
}
}";
因为它是 JSON,您可以使用单引号而不是双引号。
关于“@”:Multiline String Literal in C#
如果您真的 需要在字符串文字中执行此操作,我会使用逐字字符串文字(@
前缀)。在逐字字符串文字中,您需要使用 ""
来表示双引号。我建议也使用内插字符串文字,以使 title
和 message
的嵌入更清晰。这确实意味着您需要将 {{
和 }}
加倍。所以你会:
string title = "This is the title: ";
string message = "(Message)";
string str = $@"
{{
""aps"":
{{
""alert"":""{title}{message}""
}}
}}";
Console.WriteLine(str);
输出:
{
"aps":
{
"alert":"This is the title: (Message)"
}
}
但是,这仍然比使用 JSON API 简单地构建 JSON 更脆弱 - 例如,如果标题或消息包含引号,您最终会得到无效 JSON。我只使用 Json.NET,例如:
string title = "This is the title: ";
string message = "(Message)";
JObject json = new JObject
{
["aps"] = new JObject
{
["alert"] = title + message
}
};
Console.WriteLine(json.ToString());
IMO 更干净,也更健壮。
例如
string str = "{\"aps\":{\"alert\":\"" + title + "" + message + "\"}}";
我需要把它写成可读性:
string str = "
{
\"aps\":
{
\"alert\":\"" + title + "" + message + "\"
}
}";
如何实现,请指教。
您可以使用 X-Tech 所说的,在每一行使用额外的连接运算符 ('+'),或使用符号 '@':
string str = @"
{
'aps':
{
'alert':'" + title + "" + message + @"'
}
}";
因为它是 JSON,您可以使用单引号而不是双引号。
关于“@”:Multiline String Literal in C#
如果您真的 需要在字符串文字中执行此操作,我会使用逐字字符串文字(@
前缀)。在逐字字符串文字中,您需要使用 ""
来表示双引号。我建议也使用内插字符串文字,以使 title
和 message
的嵌入更清晰。这确实意味着您需要将 {{
和 }}
加倍。所以你会:
string title = "This is the title: ";
string message = "(Message)";
string str = $@"
{{
""aps"":
{{
""alert"":""{title}{message}""
}}
}}";
Console.WriteLine(str);
输出:
{
"aps":
{
"alert":"This is the title: (Message)"
}
}
但是,这仍然比使用 JSON API 简单地构建 JSON 更脆弱 - 例如,如果标题或消息包含引号,您最终会得到无效 JSON。我只使用 Json.NET,例如:
string title = "This is the title: ";
string message = "(Message)";
JObject json = new JObject
{
["aps"] = new JObject
{
["alert"] = title + message
}
};
Console.WriteLine(json.ToString());
IMO 更干净,也更健壮。