C# 中的字串插補

本教學課程會示範如何使用字串插補進行格式化,並將運算式結果包含在結果字串中。 這些範例假設您熟悉 C# 基本概念和 .NET 類型格式設定。 如果您不熟悉字串插補或 .NET 類型格式設定,請先參閱互動式字串插補教學課程。 如需 .NET 中格式化類型的詳細資訊,請參閱 在 .NET 中格式化類型。

簡介

若要將字串常值識別為插入字串,請在其前面加上 $ 符號。 您可以內嵌任何有效的 C# 運算式,以在插入字串中傳回值。 在下列範例中,只要評估運算式,其結果即會轉換成字串,並包含在結果字串中:

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);
// 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

如範例所示,藉由用括號括住運算式,即可在插入字串中包含運算式:

{<interpolationExpression>}

插入字串支援字串符合格式化功能的所有功能。 相較於使用 String.Format 方法,它們是可讀性更佳的替代項目。

如何指定內插補點運算式的格式字串

若要指定運算式結果類型所支援的格式字串,請遵循內插補點運算式與冒號 (「:」) 和格式字串:

{<interpolationExpression>:<formatString>}

下列範例會示範如何針對產生日期與時間或數值結果的運算式,指定標準和自訂的格式字串:

var date = new DateTime(1731, 11, 25);
Console.WriteLine($"On {date:dddd, MMMM dd, yyyy} L. Euler introduced the letter e to denote {Math.E:F5}.");
// Output:
// On Sunday, November 25, 1731 L. Euler introduced the letter e to denote 2.71828.

如需詳細資訊,請參閱 複合格式 設定一文的 格式化字串元件 一節。

如何控制已格式化之內插補點運算式的欄位寬度和對齊

若要指定格式化運算式結果的最小欄位寬度和對齊方式,請遵循內插補點運算式與逗號 (「,」) 和常數運算式:

{<interpolationExpression>,<alignment>}

如果 alignment 值是正數,已格式化的運算式結果為靠右對齊;如果是負數,則是靠左對齊。

如果您需要指定對齊和格式字串,請從對齊元件開始:

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

下列範例會示範如何指定對齊,並使用管道字元 ("|") 來分隔文字欄位:

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}|");
// Output:
// Three classical Pythagorean means of 3 and 4:
// |Arithmetic|  3.500|
// |Geometric|  3.464|
// |Harmonic |  3.429|

如範例輸出所示,如果已格式化的運算式結果長度超過指定的欄位寬度,則會忽略 alignment 值。

如需詳細資訊,請參閱 複合格式 設定一文的 對齊元件 一節。

如何在插入字串中使用逸出序列

插入字串支援可用於一般字串常值中所有逸出序列。 如需詳細資訊,請參閱字串逸出序列

若要逐字解譯逸出序列,請使用逐字字串常值。 插入的逐字字串會以 和 @ 字元開頭 $ 。 您可以依任何順序使用 $@$@"..."@$"..." 都是有效的插補逐字字串。

若要在結果字串中包含大括號 "{" 或 "}",請使用兩個大括號 "{{" 或 "}}"。 如需詳細資訊,請參閱 複合格式 設定一文的 逸出大 括弧一節。

下列範例會示範如何在結果字串中包含大括號,並建構逐字插入字串:

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.");
// Output:
// Find the intersection of the {1, 2, 7, 9} and {7, 9, 12} sets.

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

從 C# 11 開始,您可以使用 插入的原始字串常值

如何在內插補點運算式中使用三元條件運算子 ?:

因為冒號 (":") 在內插補點運算式的項目中具有特殊意義,為了在運算式中使用條件運算子,請用括弧括住運算式,如下列範例所示:

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

如何使用字串插補建立文化特性特有的結果字串

根據預設,插入字串會使用 CultureInfo.CurrentCulture 屬性針對所有格式設定作業所定義的目前文化特性。

從 .NET 6 開始,您可以使用 String.Create(IFormatProvider, DefaultInterpolatedStringHandler) 方法來將插入字串解析為特定文化特性的結果字串,如下列範例所示:

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;
foreach (var culture in cultures)
{
    var cultureSpecificMessage = string.Create(culture, $"{date,23}{number,20:N3}");
    Console.WriteLine($"{culture.Name,-10}{cultureSpecificMessage}");
}
// Output is similar to:
// en-US       8/27/2023 12:35:31 PM      31,415,926.536
// en-GB         27/08/2023 12:35:31      31,415,926.536
// nl-NL         27-08-2023 12:35:31      31.415.926,536
//               08/27/2023 12:35:31      31,415,926.536

在舊版 .NET 中,使用插入字串 System.FormattableString 隱含轉換成 實例,並呼叫其 ToString(IFormatProvider) 方法來建立特定文化特性的結果字串。 下列範例顯示如何執行該項工作:

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,23}{number,20:N3}";
foreach (var culture in cultures)
{
    var cultureSpecificMessage = message.ToString(culture);
    Console.WriteLine($"{culture.Name,-10}{cultureSpecificMessage}");
}
// Output is similar to:
// en-US       8/27/2023 12:35:31 PM      31,415,926.536
// en-GB         27/08/2023 12:35:31      31,415,926.536
// nl-NL         27-08-2023 12:35:31      31.415.926,536
//               08/27/2023 12:35:31      31,415,926.536

如範例所示,您可以使用一個 FormattableString 執行個體,針對各種文化特性產生多個結果字串。

如何建立使用不因文化特性而異的結果字串

從 .NET 6 開始,使用 String.Create(IFormatProvider, DefaultInterpolatedStringHandler) 方法將插入字串解析為 的結果字串 InvariantCulture ,如下列範例所示:

string message = string.Create(CultureInfo.InvariantCulture, $"Date and time in invariant culture: {DateTime.Now}");
Console.WriteLine(message);
// Output is similar to:
// Date and time in invariant culture: 05/17/2018 15:46:24

在舊版 .NET 和 方法中 FormattableString.ToString(IFormatProvider) ,您可以使用靜態 FormattableString.Invariant 方法,如下列範例所示:

string message = FormattableString.Invariant($"Date and time in invariant culture: {DateTime.Now}");
Console.WriteLine(message);
// Output is similar to:
// Date and time in invariant culture: 05/17/2018 15:46:24

結論

本教學課程描述了使用字串插補的常見案例。 如需字串插補的詳細資訊,請參閱 字串插 補。 如需 .NET 中格式化類型的詳細資訊,請參閱 .NET 複合格式設定文章中的格式化 類型。

另請參閱