共用方式為


C# 中的字串插補

本教學課程說明如何使用 字串插補 來格式化和包含結果字串中的表達式結果。 這些範例假設您已熟悉基本的 C# 概念和 .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 方法的更易讀替代方案。 每個插補字串都必須具有:

  • 開頭引號字元之前是以 $ 字元開頭的字串常值。 符號與引號字元之間 $ 不能有任何空格。
  • 一或多個 插補表達式。 您通過開括號和閉括號({})來表示插值表達式。 您可以將任何傳回值 (包括 null) 的 C# 運算式放在大括弧內。

C# 會根據下列規則來評估{}字元之間的運算式:

  • 如果插補表示式評估為 null,則會使用空字串 (“” 或 String.Empty) 。
  • 如果插補表達式未能評估為 null,通常會呼叫結果類型的 ToString 方法。

如何指定插補表達式的格式字串

若要指定由表示式結果類型所支援的格式字串,請在內插表示式後加上冒號(:)和格式字串。

{<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>,<width>}

下列程式代碼範例會使用最小欄位寬度來建立表格式輸出:

var titles = new Dictionary<string, string>()
{
    ["Doyle, Arthur Conan"] = "Hound of the Baskervilles, The",
    ["London, Jack"] = "Call of the Wild, The",
    ["Shakespeare, William"] = "Tempest, The"
};

Console.WriteLine("Author and Title List");
Console.WriteLine();
Console.WriteLine($"|{"Author",-25}|{"Title",30}|");
foreach (var title in titles)
{
    Console.WriteLine($"|{title.Key,-25}|{title.Value,30}|");
}
// Output:
// Author and Title List
// 
// |Author                   |Title                          |
// |Doyle, Arthur Conan      |Hound of the Baskervilles, The |
// |London, Jack             |         Call of the Wild, The |
// |Shakespeare, William     |                  Tempest, The |

如果 寬度 值為正數,則格式化的表達式結果會靠右對齊;如果為負數,則為靠左對齊。 -拿掉寬度規範之前的符號,然後再次執行範例以查看結果。

如果您需要同時指定寬度和格式字串,請從寬度元件開始:

{<interpolationExpression>,<width>:<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|

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

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

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

內插字串支援所有可以在一般字串常值中使用的跳脫序列。 如需詳細資訊,請參閱 字串逸出序列

若要以字面方式解讀跳脫序列,請使用逐字串字面常值。 插值的逐字字串會以$@字元開頭。 您可以依任何順序使用 $@$@"..."@$"..." 都是有效的差補逐字字串。

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

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

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 和複合格式設定文章中的格式化類型

另請參閱