“$”符号在C#6.0中有什么作用?

时间:2015-05-12 15:10:27

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

在MVC 6源代码中,我看到一些代码行,其字符串以$符号开头。

正如我以前从未见过的那样,我认为它在C#6.0中是新的。我不确定。 (我希望我是对的,否则我会感到震惊,因为我从来没有碰过它。

就像:

var path = $"'{pathRelative}'";

1 个答案:

答案 0 :(得分:18)

你说得对,这是一个新的C#6功能。

字符串前的$符号启用字符串插值。编译器将特别解析字符串,并且将评估花括号内的任何表达式并将其插入到字符串中。

在引擎盖下,它转换为与此相同的东西:

var path = string.Format("'{0}'", pathRelative);

让我们看一下这个代码片段的IL:

var test = "1";
var val1 = $"{test}";
var val2 = string.Format("{0}", test);

编译为:

// var test = "1";
IL_0001: ldstr "1"
IL_0006: stloc.0

// var val1 = $"{test}";
IL_0007: ldstr "{0}"
IL_000c: ldloc.0
IL_000d: call string [mscorlib]System.String::Format(string, object)
IL_0012: stloc.1

// var val2 = string.Format("{0}", test);
IL_0013: ldstr "{0}"
IL_0018: ldloc.0
IL_0019: call string [mscorlib]System.String::Format(string, object)
IL_001e: stloc.2

所以这两个在编译的应用程序中是相同的。

关于C#字符串插值语法的注释:不幸的是,现在字符串插值的水域变得混乱,因为原始的C#6预览有一个different syntax,早期在博客上得到了很多关注。您仍然会看到很多使用反斜杠进行字符串插值的引用,但这在语法上不再有效。