return $“({x},{y})”; in c# Can you explain what is $ doing there?
这是密码
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Coords { public int x, y; public Coords() { x = 0; y = 0; } public override string ToString() { return $"({x},{y})"; } } |
你能解释一下
第一个问题。
Can you explain what is $ doing there?
Ans:
The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolated expressions. When an interpolated string is resolved to a result string, items with interpolated expressions are replaced by the string representations of the expression results. This feature is available in C# 6 and later versions of the language.
您可以在这里阅读更多关于插值的内容
第二个问题。
I tried to run it but it showed a compilation error.
Ans:
从此处删除空间
1 2 | return $"({x},{y})" ^ |
所以它变成了
1 | return $"({x},{y})"; |
如果使用低于6的C版本,则这将与插值相同。
1 | return string.Format("({0},{1})", x, y); |
$是string.format的缩写,用于字符串插入,这是C 6的一个新特性。看到这里
在你的情况下,它与
string.Format("({0},{1})", x, y);
但是在$和"之间不允许有空格。所以你应该使用
$"({x},{y})" (no space after $)
C 5或更低版本中不提供供您参考
这是一个字符串插值运算符。$字符串插值
它允许您在字符串块中插入C表达式。代码的问题似乎是$operator和字符串之间不必要的空格。
这就是所谓的字符串插值
1 2 3 4 | public override string ToString() { return $"({x},{y})"; } |
这个是一样的
1 2 3 4 | public override string ToString() { return"(" + x +"," + y +")"; } |