问题描述
在MVC 6源代码中,我看到了字符串以$领先的迹象一些代码行。
In MVC 6 source code I saw some code lines that has strings leading with $ signs.
正如我以前从未看到它,我认为这是在C#中新6.0。我不确定。 (我希望我是对的,否则我从未进过它,我会感到震惊。
As I never saw it before, I think it is new in C# 6.0. I'm not sure. (I hope I'm right, otherwise I'd be shocked as I never crossed it before.
这是这样的:
var path = $"'{pathRelative}'";
推荐答案
你是正确的,这是一个新的C#6功能。
You're correct, this is a new C# 6 feature.
$
字符串之前签署允许串插,编译器将专门解析字符串,大括号内的任何表达式将被计算并插入到位字符串。
The $
sign before a string enables string interpolation. The compiler will parse the string specially, and any expressions inside curly braces will be evaluated and inserted into the string in place.
在将其转换为同样的事情,因为这罩:
Under the hood it converts to the same thing as this:
var path = string.Format("'{0}'", pathRelative);
让我们看看IL这个片断:
Let's look at the IL for this snippet:
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
于是两人都是在编译的应用程序是相同的。
So the two are identical in the compiled application.
C#的串插语法的说明:不幸的是,水被搅浑,现在就串插,因为原来的C#6预览过的 。你还是会看到很多参考使用字符串插值反斜杠,但这已不再是语法上有效。
A note on the C# string interpolation syntax: Unfortunately the waters are muddied right now on string interpolation because the original C# 6 preview had a different syntax that got a lot of attention on blogs early on. You'll still see a lot of references to using backslashes for string interpolation, but this is no longer syntactically valid.
这篇关于什么是“$”标志而在C#6.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!