$ - 字串插值(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.

隱含轉換並如何指定IFormatProviderImplicit conversions and how to specify IFormatProvider implementation

有三個來自插入字串的隱含轉換: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 can also use the ToString(IFormatProvider) method to provide a user-defined implementation of the IFormatProvider interface that supports custom formatting. 有關詳細資訊,請參閱.NET 文章中的格式格式類型的「使用 ICustomFor物質」部分的自訂格式。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 can also 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