使用字符串插值的字符串连接

String concatenation using String interpolation

我有类似下面的内容。

var amount = ",000.99";
var formattedamount = string.Format("{0}{1}{0}", "\"", amount);

如何使用字符串插值实现同样的效果?

我试过如下

var formattedamount1 = $"\"{amount}\"";

有没有更好的方法使用字符串插值来做到这一点?

同样的事情你可以通过做来实现:

var formattedamount1 = $"\"{amount}\"";

var formattedamount1 = $@"""{amount}""";

它基本上允许你写 string.Format(),但不是使用一个带有 "placeholders"({0}, {1}, .. {N}) 的字符串,你直接 writing/using 你的变量在 string.

请阅读有关 String Interpolation (DotNetPerls), $ - string interpolation 的更多信息,以充分了解发生了什么。

更新

Is there any better way of doing this using string interpolation

不,这只是字符串插值,你不能让下面的内容更短更易读

var formattedamount1 = $"\"{amount}\"";

原回答

$ - string interpolation (C# Reference)

To include a brace, "{" or "}", in the text produced by an interpolated string, use two braces, "{{" or "}}". For more information, see Escaping Braces.

引号正常转义

例子

string name = "Horace";
int age = 34;

Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");

输出

He asked, "Is your name Horace?", but didn't wait for a reply :-{
Horace is 34 years old.

再给一个选项,如果你想确保在开头和结尾使用相同的引号,你可以为此使用一个单独的变量:

string quote = "\"";
string amount = ",000.99";
string formattedAmount = $"{quote}{amount}{quote}";

我不确定我个人是否会为此烦恼,但这是另一种可以考虑的选择。