如何在C#6.0字符串插值中输入引号字符

时间:2015-06-28 13:32:56

标签: c# string-interpolation c#-6.0

鉴于

IDictionary<string, string> x;

以前你可以做(​​作为带引号的参数代码示例):

string.Format("{0}", x["y"]);

格式化C#6.0字符串插值的正确方法是什么?

$"{x["y"]}"   // compiler error due to the quotes on the indexer value
              // UPDATE:  actually does work, must have had another typo I missed

将引号转义为

\"

无法正常工作

 var b = "y";
 ...
 $"{x[b]}"

似乎很尴尬。

1 个答案:

答案 0 :(得分:7)

这对我有用:

var dictionary= new Dictionary<string, string>();
dictionary.Add("x","value of x");
Console.WriteLine($"x is {dictionary["x"]}");

确保您的项目设置为使用C#语言级别的6.0版本(这是VS2015上的默认选项)。

编辑:您也可以尝试here。 (请务必查看“C#6.0 Beta”)。