我打算使用逐字字符串,但我错误地输入$而不是@。
但是编译器没有给我任何错误,并成功编译。
我想知道它是什么,有什么作用。我找过了,但什么也没找到。
然而,它不像一个逐字字符串,因为我不能写:
string str = $"text\";
在c#中字符串前面的$字符是什么意思?
string str = $"text";
我使用Visual studio 2015 CTP。
我打算使用逐字字符串,但我错误地输入$而不是@。
但是编译器没有给我任何错误,并成功编译。
我想知道它是什么,有什么作用。我找过了,但什么也没找到。
然而,它不像一个逐字字符串,因为我不能写:
string str = $"text\";
在c#中字符串前面的$字符是什么意思?
string str = $"text";
我使用Visual studio 2015 CTP。
当前回答
字符串中的$符号用于插值字符串的定义,这是c#中的一个特性,用于插值字符串是一个可能包含插值表达式的“真字符串”
为了获得更多信息,以下是答案和示例的来源: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
其他回答
下面的示例强调了使用插值字符串相对于string.Format()在简洁和可读性方面的各种优点。它还显示{}内的代码像任何其他函数参数一样被求值,就像调用string.Format()一样。
using System;
public class Example
{
public static void Main()
{
var name = "Horace";
var age = 34;
// replaces {name} with the value of name, "Horace"
var s1 = $"He asked, \"Is your name {name}?\", but didn't wait for a reply.";
Console.WriteLine(s1);
// as age is an integer, we can use ":D3" to denote that
// it should have leading zeroes and be 3 characters long
// see https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros
//
// (age == 1 ? "" : "s") uses the ternary operator to
// decide the value used in the placeholder, the same
// as if it had been placed as an argument of string.Format
//
// finally, it shows that you can actually have quoted strings within strings
// e.g. $"outer { "inner" } string"
var s2 = $"{name} is {age:D3} year{(age == 1 ? "" : "s")} old.";
Console.WriteLine(s2);
}
}
// The example displays the following output:
// He asked, "Is your name Horace?", but didn't wait for a reply.
// Horace is 034 years old.
我不知道它是如何工作的,但你也可以用它来标记你的值!
例子:
Console.WriteLine($"I can tab like {"this !", 5}.");
当然,您可以将“this !”替换为任何变量或任何有意义的内容,就像您也可以更改选项卡一样。
注意,你也可以将两者结合起来,这很酷(尽管看起来有点奇怪):
// simple interpolated verbatim string
WriteLine($@"Path ""C:\Windows\{file}"" not found.");
字符串中的$符号用于插值字符串的定义,这是c#中的一个特性,用于插值字符串是一个可能包含插值表达式的“真字符串”
为了获得更多信息,以下是答案和示例的来源: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
$是字符串的简写。格式和字符串插值一起使用,这是c# 6的一个新特性。正如在您的例子中使用的那样,它什么也不做,就像string.Format()一样。
当使用它来构建引用其他值的字符串时,它就发挥了作用。以前必须写成:
var anInt = 1;
var aBool = true;
var aString = "3";
var formated = string.Format("{0},{1},{2}", anInt, aBool, aString);
现在就变成:
var anInt = 1;
var aBool = true;
var aString = "3";
var formated = $"{anInt},{aBool},{aString}";
还有一种不太为人所知的字符串插值形式,使用$@(两个符号的顺序很重要)。它允许@""字符串的特性与$""混合,以支持字符串插值,而不需要在整个字符串中使用\\。下面这两行:
var someDir = "a";
Console.WriteLine($@"c:\{someDir}\b\c");
将输出:
c:\a\b\c