$ - 字符串内插(C# 参考)$ - string interpolation (C# reference)

$ 特殊字符将字符串文本标识为内插字符串 。The $ special character identifies a string literal as an interpolated string. 内插字符串是可能包含内插表达式的字符串文本 。An interpolated string is a string literal that might contain interpolation expressions. 将内插字符串解析为结果字符串时,带有内插表达式的项会替换为表达式结果的字符串表示形式。When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results. 从 C# 6 开始可以使用此功能。This feature is available starting with C# 6.

与使用字符串复合格式设置功能创建格式化字符串相比,字符串内插提供的语法更具可读性,且更加方便。String interpolation provides a more readable and convenient syntax to create formatted strings than a string composite formatting feature. 下面的示例使用了这两种功能生成同样的输出结果:The following example uses both features to produce the same output:

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.");
// Both calls produce the same output that is similar to:
// Hello, Mark! Today is Wednesday, it's 19:40 now.

内插字符串的结构Structure of an interpolated string

若要将字符串标识为内插字符串,可在该字符串前面加上 $ 符号。To identify a string literal as an interpolated string, prepend it with the $ symbol. 字符串文本开头的 $" 之间不能有任何空格。You cannot have any white space between the $ and the " that starts a string literal.

具备内插表达式的项的结构如下所示:The structure of an item with an interpolation expression is as follows:

{<interpolationExpression>[,<alignment>][:<formatString>]}

括号中的元素是可选的。Elements in square brackets are optional. 下表说明了每个元素:The following table describes each element:

元素Element 说明Description
interpolationExpression 生成需要设置格式的结果的表达式。The expression that produces a result to be formatted. null 的字符串表示形式为 String.EmptyString representation of null is String.Empty.
alignment 常数表达式,它的值定义表达式结果的字符串表示形式中的最小字符数。The constant expression whose value defines the minimum number of characters in the string representation of the expression result. 如果值为正,则字符串表示形式为右对齐;如果值为负,则为左对齐。If positive, the string representation is right-aligned; if negative, it's left-aligned. 有关详细信息,请参阅对齐组件For more information, see Alignment Component.
formatString 受表达式结果类型支持的格式字符串。A format string that is supported by the type of the expression result. 有关更多信息,请参阅格式字符串组件For more information, see Format String Component.

以下示例使用上述可选的格式设置组件:The following example uses optional formatting components described above:

Console.WriteLine($"|{"Left",-7}|{"Right",7}|");

const int FieldWidthRightAligned = 20;
Console.WriteLine($"{Math.PI,FieldWidthRightAligned} - default formatting of the pi number");
Console.WriteLine($"{Math.PI,FieldWidthRightAligned:F3} - display only three decimal digits of the pi number");
// Expected output is:
// |Left   |  Right|
//     3.14159265358979 - default formatting of the pi number
//                3.142 - display only three decimal digits of the pi number    

特殊字符Special characters

要在内插字符串生成的文本中包含大括号 "{" 或 "}",请使用两个大括号,即 "{{" 或 "}}"。To include a brace, "{" or "}", in the text produced by an interpolated string, use two braces, "{{" or "}}". 有关详细信息,请参阅转义大括号For more information, see Escaping Braces.

因为冒号(“:”)在内插表达式项中具有特殊含义,为了在内插表达式中使用条件运算符,请将表达式放在括号内。As the colon (":") has special meaning in an interpolation expression item, in order to use a conditional operator in an interpolation expression, enclose that expression in parentheses.

以下示例演示如何将大括号含入结果字符串中,以及如何在内插表达式中使用条件运算符:The following example shows how to include a brace in a result string and how to use a conditional operator in an interpolation expression:

string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
// Expected output is:
// He asked, "Is your name Horace?", but didn't wait for a reply :-{
// Horace is 34 years old.

内插逐字字符串以 $ 字符开头,后跟 @ 字符。An interpolated verbatim string starts with the $ character followed by the @ character. 有关逐字字符串的详细信息,请参阅字符串逐字标识符主题。For more information about verbatim strings, see the string and verbatim identifier topics.

备注

从 C# 8.0 开始,可以按任意顺序使用 $@ 标记:$@"..."@$"..." 均为有效的内插逐字字符串。Starting with C# 8.0, you can use the $ and @ tokens in any order: both $@"..." and @$"..." are valid interpolated verbatim strings. 在早期 C# 版本中,$ 标记必须出现在 @ 标记之前。In earlier C# versions, the $ token must appear before the @ token.

隐式转换和指定 IFormatProvider 实现的方式Implicit conversions and how to specify IFormatProvider implementation

内插字符串有 3 种隐式转换:There are three implicit conversions from an interpolated string:

  1. 将内插字符串转换为 String 实例,该类例是内插字符串的解析结果,其中内插表达式项被替换为结果的格式设置正确的字符串表示形式。Conversion of an interpolated string to a String instance that is the result of interpolated string resolution with interpolation expression items being replaced with the properly formatted string representations of their results. 此转换使用 CurrentCulture 设置表达式结果的格式。This conversion uses the CurrentCulture to format expression results.

  2. 将内插字符串转换为表示复合格式字符串的 FormattableString 实例,同时也将表达式结果格式化。Conversion of an interpolated string to a FormattableString instance that represents a composite format string along with the expression results to be formatted. 这允许通过单个 FormattableString 实例创建多个包含区域性特定内容的结果字符串。That allows you to create multiple result strings with culture-specific content from a single FormattableString instance. 要执行此操作,请调用以下方法之一:To do that, call one of the following methods:

    你还可使用 ToString(IFormatProvider) 方法,以提供支持自定义格式设置的 IFormatProvider 接口的用户定义实现。You also can use the ToString(IFormatProvider) method to provide a user-defined implementation of the IFormatProvider interface that supports custom formatting. 有关详细信息,请参阅在 .NET 中设置类型格式一文中的使用 ICustomFormatter 进行自定义格式设置部分。For more information, see the Custom formatting with ICustomFormatter section of the Formatting types in .NET article.

  3. 将内插字符串转换为 IFormattable 实例,使用此实例也可通过单个 IFormattable 实例创建多个包含区域性特定内容的结果字符串。Conversion of an interpolated string to an IFormattable instance that also allows you to create multiple result strings with culture-specific content from a single IFormattable instance.

以下示例通过隐式转换为 FormattableString 来创建特定于区域性的结果字符串:The following example uses implicit conversion to FormattableString to create culture-specific result strings:

double speedOfLight = 299792.458;
FormattableString message = $"The speed of light is {speedOfLight:N3} km/s.";

System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("nl-NL");
string messageInCurrentCulture = message.ToString();

var specificCulture = System.Globalization.CultureInfo.GetCultureInfo("en-IN");
string messageInSpecificCulture = message.ToString(specificCulture);

string messageInInvariantCulture = FormattableString.Invariant(message);

Console.WriteLine($"{System.Globalization.CultureInfo.CurrentCulture,-10} {messageInCurrentCulture}");
Console.WriteLine($"{specificCulture,-10} {messageInSpecificCulture}");
Console.WriteLine($"{"Invariant",-10} {messageInInvariantCulture}");
// Expected output is:
// nl-NL      The speed of light is 299.792,458 km/s.
// en-IN      The speed of light is 2,99,792.458 km/s.
// Invariant  The speed of light is 299,792.458 km/s.

其他资源Additional resources

如果你不熟悉字符串内插,请参阅 C# 中的字符串内插交互式教程。If you are new to string interpolation, see the String interpolation in C# interactive tutorial. 还可查看另一个 C# 中的字符串内插教程,该教程演示如何使用内插字符串生成带格式的字符串。You also can check another String interpolation in C# tutorial that demonstrates how to use interpolated strings to produce formatted strings.

内插字符串编译Compilation of interpolated strings

如果内插字符串类型为 string,则通常将其转换为 String.Format 方法调用。If an interpolated string has the type string, it's typically transformed into a String.Format method call. 如果分析的行为等同于串联,则编译器可将 String.Format 替换为 String.ConcatThe compiler may replace String.Format with String.Concat if the analyzed behavior would be equivalent to concatenation.

如果内插字符串类型为 IFormattableFormattableString,则编译器会生成对 FormattableStringFactory.Create 方法的调用。If an interpolated string has the type IFormattable or FormattableString, the compiler generates a call to the FormattableStringFactory.Create method.

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范内插字符串部分。For more information, see the Interpolated strings section of the C# language specification.

请参阅See also