$ - 字串內插補點 (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 in C# 6 and later versions of the language.

字串插補在建立格式化字串時,是比字串複合格式化功能更容易理解且方便的語法。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. 這樣做會導致編譯時期錯誤。Doing so causes a compile-time error.

具有內插補點運算式的項目結構如下所示: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 the null result is String.Empty.
alignment 常數的運算式,其值定義內插補點運算式結果之字串表示的字元數下限。The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolation expression. 如果是正數,則字串表示是靠右對齊;如果是負數,它是靠左對齊。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.

逐字插入字串以 $ 字元為開頭,後面接著 @ 字元。A verbatim interpolated string starts with the $ character followed by the @ character. 如需逐字字串的詳細資訊,請參閱字串逐字識別碼主題。For more information about verbatim strings, see the string and verbatim identifier topics.

注意

$ 語彙基元必須出現在逐字內插字串中的 @ 語彙基元之前。The $ token must appear before the @ token in a verbatim interpolated string.

隱含轉換和指定 IFormatProvider 實作Implicit conversions and specifying 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. 這項轉換會使用目前文化特性。This conversion uses the current culture.

  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. 如需詳細資訊,請參閱使用 ICustomFormatter 的自訂格式For more information, see Custom Formatting with ICustomFormatter.

  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