$说明
- $ 特殊字符将字符串文本标识为内插字符串 。 内插字符串是可能包含内插表达式的字符串文本 。
将内插字符串解析为结果字符串时,带有内插表达式的项会替换为表达式结果的字符串表示形式。 从 C# 6 开始可以使用此功能
若要将字符串标识为内插字符串,可在该字符串前面加上 $ 符号。 字符串字面量开头的 $ 和 " 之间不能有任何空格。
具备内插表达式的项的结构如下所示:
{<interpolationExpression>[,<alignment>][:<formatString>]}
string name = "Mark";
var date = DateTime.Now;
// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// String interpolation:
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
@说明
指示将原义解释字符串。 @ 字符在此实例中定义原义标识符。 简单转义序列(如代表反斜杠的 “\”)、
- 十六进制转义序列(如代表大写字母 A 的 “\x0041”)和 Unicode 转义序列(如代表大写字母 A 的
“\u0041”)都将按字面解释。 只有引号转义序列 ("") 不会按字面解释;因为它生成一个双引号。
此外,如果是逐字内插字符串,大括号转义序列( 和 }})不按字面解释;它们会生成单个大括号字符。
下面的示例分别使用常规字符串和原义字符串定义两个相同的文件路径。 这是原义字符串的较常见用法之一
。
string filename1 = @"c:\documents\files\u0066.txt";
string filename2 = "c:\\documents\\files\\u0066.txt";
Console.WriteLine(filename1);
Console.WriteLine(filename2);
// The example displays the following output:
// He said, "This is the last chance!"
// He said, "This is the last \u0063hance\x0021"
- 下面的示例演示定义包含相同字符序列的常规字符串和原义字符串的效果。
string s1 = "He said, \"This is the last \u0063hance\x0021\"";
string s2 = @"He said, ""This is the last \u0063hance\x0021""";
Console.WriteLine(s1);
Console.WriteLine(s2);
// The example displays the following output:
// He said, "This is the last chance!"
// He said, "This is the last \u0063hance\x0021"