C# 中的字串插補String interpolation in C#

本教學課程會示範如何使用字串插補進行格式化,並將運算式結果包含在結果字串中。This tutorial shows you how to use string interpolation to format and include expression results in a result string. 這些範例假設您熟悉 C# 基本概念和 .NET 類型格式設定。The examples assume that you are familiar with basic C# concepts and .NET type formatting. 如果您不熟悉字串插補或 .NET 類型格式設定,請先參閱互動式字串插補教學課程If you are new to string interpolation or .NET type formatting, check out the interactive string interpolation tutorial first. 如需在 .NET 中格式化類型的詳細資訊,請參閱在 .NET 中格式化類型主題。For more information about formatting types in .NET, see the Formatting Types in .NET topic.

注意

本文中的 C# 範例會在 Try.NET 內嵌程式碼執行器和測試區執行。The C# examples in this article run in the Try.NET inline code runner and playground. 選取 [執行] 按鈕以在互動式視窗中執行範例。Select the Run button to run an example in an interactive window. 執行程式碼之後,您便可以修改它,並再選取一次 [執行] 來執行修改過的程式碼。Once you execute the code, you can modify it and run the modified code by selecting Run again. 修改過的程式碼會在互動式視窗中執行,或是如果編譯失敗的話,互動式視窗會顯示所有 C# 編譯器錯誤訊息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

簡介Introduction

字串插補功能是以複合格式功能為基礎建置而成,可提供更容易理解且方便的語法,在結果字串中包含已格式化的運算式結果。The string interpolation feature is built on top of the composite formatting feature and provides a more readable and convenient syntax to include formatted expression results in a result string.

若要將字串常值識別為插入字串,請在其前面加上 $ 符號。To identify a string literal as an interpolated string, prepend it with the $ symbol. 您可以內嵌任何有效的 C# 運算式,以在插入字串中傳回值。You can embed any valid C# expression that returns a value in an interpolated string. 在下列範例中,只要評估運算式,其結果即會轉換成字串,並包含在結果字串中:In the following example, as soon as an expression is evaluated, its result is converted into a string and included in a result string:

double a = 3;
double b = 4;
Console.WriteLine($"Area of the right triangle with legs of {a} and {b} is {0.5 * a * b}");
Console.WriteLine($"Length of the hypotenuse of the right triangle with legs of {a} and {b} is {CalculateHypotenuse(a, b)}");

double CalculateHypotenuse(double leg1, double leg2) => Math.Sqrt(leg1 * leg1 + leg2 * leg2);

// Expected output:
// Area of the right triangle with legs of 3 and 4 is 6
// Length of the hypotenuse of the right triangle with legs of 3 and 4 is 5

如範例所示,藉由用括號括住運算式,即可在插入字串中包含運算式:As the example shows, you include an expression in an interpolated string by enclosing it with braces:

{<interpolationExpression>}

插入字串支援字串符合格式化功能的所有功能。Interpolated strings support all the capabilities of the string composite formatting feature. 相較於使用 String.Format 方法,它們是可讀性更佳的替代項目。That makes them a more readable alternative to the use of the String.Format method.

如何指定內插補點運算式的格式字串How to specify a format string for an interpolation expression

在內插補點運算式後面接著冒號 (":") 和格式字串,即可指定運算式結果類型所支援的格式字串:You specify a format string that is supported by the type of the expression result by following the interpolation expression with a colon (":") and the format string:

{<interpolationExpression>:<formatString>}

下列範例會示範如何針對產生日期與時間或數值結果的運算式,指定標準和自訂的格式字串:The following example shows how to specify standard and custom format strings for expressions that produce date and time or numeric results:

var date = new DateTime(1731, 11, 25);
Console.WriteLine($"On {date:dddd, MMMM dd, yyyy} Leonhard Euler introduced the letter e to denote {Math.E:F5} in a letter to Christian Goldbach.");

// Expected output:
// On Sunday, November 25, 1731 Leonhard Euler introduced the letter e to denote 2.71828 in a letter to Christian Goldbach.

如需詳細資訊,請參閱複合格式主題的格式字串元件一節。For more information, see the Format String Component section of the Composite Formatting topic. 該節中提供了一些主題連結,以描述 .NET 基底類型所支援的標準和自訂格式字串。That section provides links to the topics that describe standard and custom format strings supported by .NET base types.

如何控制已格式化之內插補點運算式的欄位寬度和對齊How to control the field width and alignment of the formatted interpolation expression

在內插補點運算式後面接著逗號 (",") 和常數運算式,即可指定已格式化之運算式結果的最小欄位寬度和對齊:You specify the minimum field width and the alignment of the formatted expression result by following the interpolation expression with a comma (",") and the constant expression:

{<interpolationExpression>,<alignment>}

如果 alignment 值是正數,已格式化的運算式結果為靠右對齊;如果是負數,則是靠左對齊。If the alignment value is positive, the formatted expression result is right-aligned; if negative, it's left-aligned.

如果您需要指定對齊和格式字串,請從對齊元件開始:If you need to specify both alignment and a format string, start with the alignment component:

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

下列範例會示範如何指定對齊,並使用管道字元 ("|") 來分隔文字欄位:The following example shows how to specify alignment and uses pipe characters ("|") to delimit text fields:

const int NameAlignment = -9;
const int ValueAlignment = 7;

double a = 3;
double b = 4;
Console.WriteLine($"Three classical Pythagorean means of {a} and {b}:");
Console.WriteLine($"|{"Arithmetic",NameAlignment}|{0.5 * (a + b),ValueAlignment:F3}|");
Console.WriteLine($"|{"Geometric",NameAlignment}|{Math.Sqrt(a * b),ValueAlignment:F3}|");
Console.WriteLine($"|{"Harmonic",NameAlignment}|{2 / (1 / a + 1 / b),ValueAlignment:F3}|");

// Expected output:
// Three classical Pythagorean means of 3 and 4:
// |Arithmetic|  3.500|
// |Geometric|  3.464|
// |Harmonic |  3.429|

如範例輸出所示,如果已格式化的運算式結果長度超過指定的欄位寬度,則會忽略 alignment 值。As the example output shows, if the length of the formatted expression result exceeds specified field width, the alignment value is ignored.

如需詳細資訊,請參閱複合格式主題的對齊元件一節。For more information, see the Alignment Component section of the Composite Formatting topic.

如何在插入字串中使用逸出序列How to use escape sequences in an interpolated string

插入字串支援可用於一般字串常值中所有逸出序列。Interpolated strings support all escape sequences that can be used in ordinary string literals. 如需詳細資訊,請參閱字串逸出序列For more information, see String escape sequences.

若要逐字解譯逸出序列,請使用逐字字串常值。To interpret escape sequences literally, use a verbatim string literal. 逐字插入字串以 $ 字元為開頭,後面接著 @ 字元。A verbatim interpolated string starts with the $ character followed by the @ character.

若要在結果字串中包含大括號 "{" 或 "}",請使用兩個大括號 "{{" 或 "}}"。To include a brace, "{" or "}", in a result string, use two braces, "{{" or "}}". 如需詳細資訊,請參閱複合格式主題的逸出大括號一節。For more information, see the Escaping Braces section of the Composite Formatting topic.

下列範例會示範如何在結果字串中包含大括號,並建構逐字插入字串:The following example shows how to include braces in a result string and construct a verbatim interpolated string:

var xs = new int[] { 1, 2, 7, 9 };
var ys = new int[] { 7, 9, 12 };
Console.WriteLine($"Find the intersection of the {{{string.Join(", ",xs)}}} and {{{string.Join(", ",ys)}}} sets.");

var userName = "Jane";
var stringWithEscapes = $"C:\\Users\\{userName}\\Documents";
var verbatimInterpolated = $@"C:\Users\{userName}\Documents";
Console.WriteLine(stringWithEscapes);
Console.WriteLine(verbatimInterpolated);

// Expected output:
// Find the intersection of the {1, 2, 7, 9} and {7, 9, 12} sets.
// C:\Users\Jane\Documents
// C:\Users\Jane\Documents

如何在內插補點運算式中使用三元條件運算子 ?:How to use a ternary conditional operator ?: in an interpolation expression

因為冒號 (":") 在內插補點運算式的項目中具有特殊意義,為了在運算式中使用條件運算子,請用括弧括住運算式,如下列範例所示:As the colon (":") has special meaning in an item with an interpolation expression, in order to use a conditional operator in an expression, enclose it in parentheses, as the following example shows:

var rand = new Random();
for (int i = 0; i < 7; i++)
{
    Console.WriteLine($"Coin flip: {(rand.NextDouble() < 0.5 ? "heads" : "tails")}");
}

如何使用字串插補建立文化特性特有的結果字串How to create a culture-specific result string with string interpolation

根據預設,插入字串會使用 CultureInfo.CurrentCulture 屬性針對所有格式設定作業所定義的目前文化特性。By default, an interpolated string uses the current culture defined by the CultureInfo.CurrentCulture property for all formatting operations. 請使用插入字串到 System.FormattableString 執行個體的隱含轉換,並呼叫其 ToString(IFormatProvider) 方法來建立文化特性特有的結果字串。Use implicit conversion of an interpolated string to a System.FormattableString instance and call its ToString(IFormatProvider) method to create a culture-specific result string. 下列範例顯示如何執行該項工作:The following example shows how to do that:

var cultures = new System.Globalization.CultureInfo[]
{
    System.Globalization.CultureInfo.GetCultureInfo("en-US"),
    System.Globalization.CultureInfo.GetCultureInfo("en-GB"),
    System.Globalization.CultureInfo.GetCultureInfo("nl-NL"),
    System.Globalization.CultureInfo.InvariantCulture
};

var date = DateTime.Now;
var number = 31_415_926.536;
FormattableString message = $"{date,20}{number,20:N3}";
foreach (var culture in cultures)
{
    var cultureSpecificMessage = message.ToString(culture);
    Console.WriteLine($"{culture.Name,-10}{cultureSpecificMessage}");
}

// Expected output is like:
// en-US       5/17/18 3:44:55 PM      31,415,926.536
// en-GB      17/05/2018 15:44:55      31,415,926.536
// nl-NL        17-05-18 15:44:55      31.415.926,536
//            05/17/2018 15:44:55      31,415,926.536

如範例所示,您可以使用一個 FormattableString 執行個體,針對各種文化特性產生多個結果字串。As the example shows, you can use one FormattableString instance to generate multiple result strings for various cultures.

如何建立使用不因文化特性而異的結果字串How to create a result string using the invariant culture

除了 FormattableString.ToString(IFormatProvider) 方法之外,您還可以使用靜態 FormattableString.Invariant 方法將插入字串解析為 InvariantCulture 的結果字串。Along with the FormattableString.ToString(IFormatProvider) method, you can use the static FormattableString.Invariant method to resolve an interpolated string to a result string for the InvariantCulture. 下列範例顯示如何執行該項工作:The following example shows how to do that:

string messageInInvariantCulture = FormattableString.Invariant($"Date and time in invariant culture: {DateTime.Now}");
Console.WriteLine(messageInInvariantCulture);

// Expected output is like:
// Date and time in invariant culture: 05/17/2018 15:46:24

結論Conclusion

本教學課程描述了使用字串插補的常見案例。This tutorial describes common scenarios of string interpolation usage. 如需字串插補的詳細資訊,請參閱字串插補主題。For more information about string interpolation, see the String interpolation topic. 如需在 .NET 中格式化類型的詳細資訊,請參閱在 .NET 中格式化類型複合格式主題。For more information about formatting types in .NET, see the Formatting Types in .NET and Composite formatting topics.

另請參閱See also