ZetCode

C# 字符串插值

上次修改时间:2025 年 4 月 18 日

本教程探讨如何在 C# 中执行字符串插值。

在 C# 中,可以使用字符串格式化或字符串插值来构造字符串。本教程侧重于后一种方法。

字符串插值涉及将表达式嵌入到字符串文字中,并将其替换为计算结果。 以 $ 字符为前缀的字符串是插值字符串,表达式用大括号 {} 括起来。

插值表达式具有以下结构

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

interpolationExpression 是计算以产生结果的表达式。 alignment 指定结果字符串表示形式的最小宽度。 formatString 定义结果的格式样式。

简单示例

此示例演示 C# 中的基本字符串插值。

Program.cs
string name = "John Doe";
int age = 34;

Console.WriteLine($"{name} is {age} years old");

DateTime now = DateTime.Now;
Console.WriteLine($"Today is {now.DayOfWeek}, it's {now:HH:mm}");

该程序创建两个具有变量和格式化日期的插值字符串。

string name = "John Doe";
int age = 34;

定义两个变量以用于第一个插值字符串。

Console.WriteLine($"{name} is {age} years old");

$ 前缀标记插值字符串,变量插入到大括号 {} 中。

$ dotnet run
John Doe is 34 years old
Today is Sunday, it's 22:12

字符串插值对齐

此示例演示如何在插值字符串中对齐文本。

Program.cs
List<User> users =
[
    new ("John", "Doe", 1230),
    new ("Lucy", "Novak", 670),
    new ("Ben", "Walter", 2050),
    new ("Robin", "Brown", 2300),
    new ("Amy", "Doe", 1250),
    new ("Joe", "Draker", 1190),
    new ("Janet", "Doe", 980),
    new ("Albert", "Novak", 1930),
];

foreach (var user in users)
{
    string fname = $"{user.FirstName} {user.LastName}";
    Console.WriteLine($"|{fname, -15}|{user.Salary, 8}|");
}

record User(string FirstName, string LastName, int Salary);

该程序显示用户列表,将姓名左对齐,薪水右对齐。

string fname = $"{user.FirstName} {user.LastName}";

使用插值将名字和姓氏组合成全名。

Console.WriteLine($"|{fname, -15}|{user.Salary, 8}|");

负对齐值将文本左对齐,而正值将其右对齐。

$ dotnet run 
|John Doe       |    1230|
|Lucy Novak     |     670|
|Ben Walter     |    2050|
|Robin Brown    |    2300|
|Amy Doe        |    1250|
|Joe Draker     |    1190|
|Janet Doe      |     980|
|Albert Novak   |    1930|

格式字符串

此示例将格式字符串应用于插值表达式。

Program.cs
DateTime now = DateTime.Now;

Console.WriteLine($"Short date: {now:d}");
Console.WriteLine($"Long date: {now:D}");
Console.WriteLine($"Short time: {now:t}");
Console.WriteLine($"Long time: {now:T}");
Console.WriteLine($"Month: {now:M}");
Console.WriteLine($"Year: {now:Y}");

该程序使用插值字符串中的各种格式说明符来格式化当前日期和时间。

$ dotnet run
Short date: 19. 1. 2024
Long date: Friday, January 19, 2024
Short time: 11:19
Long time: 11:19:22
Month: January 19
Year: January 2024

带有换行符的插值字符串

从 C# 11 开始,插值字符串可以包含换行符以提高可读性。

Program.cs
List<User> users =
[
    new ("John", "Doe", 1230),
    new ("Lucy", "Novak", 670),
    new ("Ben", "Walter", 2050),
    new ("Robin", "Brown", 2300),
    new ("Amy", "Doe", 1250),
    new ("Joe", "Draker", 1190),
    new ("Janet", "Doe", 980),
    new ("Albert", "Novak", 1930),
];

Console.WriteLine($"User with highest salary:\n{
    users.MaxBy(u => u.Salary)
}");

record User(string FirstName, string LastName, int Salary);

该程序将多行 LINQ 表达式嵌入到插值字符串中,从而增强了代码的清晰度。

$ dotnet run
User with highest salary:
User { FirstName = Robin, LastName = Brown, Salary = 2300 }

原始字符串

C# 11 中引入的原始字符串允许非转义文本,并用至少三个双引号括起来。

Program.cs
var countries = new Dictionary<string, string>
{
    {"Russia", "Moscow"},
    {"Slovakia", "Bratislava"},
    {"Germany", "Berlin"},
    {"Hungary", "Budapest"},
};

foreach (var (k, v) in countries)
{
    Console.WriteLine($"""The capital of "{k}" is "{v}"  """);
}

原始字符串简化了对带有引号的文本的处理,因为不需要转义序列。

$ dotnet run
The capital of "Russia" is "Moscow"  
The capital of "Slovakia" is "Bratislava"  
The capital of "Germany" is "Berlin"  
The capital of "Hungary" is "Budapest"  

条件运算符

在插值中使用条件运算符时,请将冒号括在括号中以避免冲突。

Program.cs
var items = new Dictionary<string, int>
{
    {"ring", 2},
    {"lamp", 1},
    {"chair", 3},
    {"coin", 5},
    {"TV", 4},
    {"book", 4},
    {"pen", 1},
};

Console.WriteLine("List of items:");

foreach (var (k, v) in items)
{
    Console.WriteLine($"""{v} {k}{(v == 1 ? "" : "s")}""");
}

该程序在插值字符串中使用条件运算符来处理复数。

$ dotnet run
List of items:
2 rings
1 lamp
3 chairs
5 coins
4 TVs
4 books
1 pen

数字格式化

此示例演示了如何在插值字符串中格式化数字。

Program.cs
double price = 49.99;
int quantity = 3;

Console.WriteLine($"Total cost: {price * quantity:C}");
Console.WriteLine($"Price per item: {price:F2}");
Console.WriteLine($"Quantity: {quantity:D3}");

该程序使用格式说明符来格式化货币、定点和填充的整数值。

$ dotnet run
Total cost: $149.97
Price per item: 49.99
Quantity: 003

带有表达式的字符串插值

插值字符串可以包含复杂的表达式以实现动态内容。

Program.cs
int x = 5;
int y = 10;

Console.WriteLine($"The sum of {x} and {y} is {x + y}");
Console.WriteLine($"The product is {x * y}");
Console.WriteLine($"Is {x} less than {y}? {(x < y ? "Yes" : "No")}");

该程序将算术和条件表达式嵌入到插值字符串中。

$ dotnet run
The sum of 5 and 10 is 15
The product is 50
Is 5 less than 10? Yes

带有集合的插值字符串

此示例使用插值来简洁地格式化集合数据。

Program.cs
List<string> fruits = ["apple", "banana", "orange"];
Console.WriteLine($"Favorite fruits: {string.Join(", ", fruits)}");
Console.WriteLine($"Total fruits: {fruits.Count}");

该程序在插值字符串中组合了集合数据和字符串连接。

$ dotnet run
Favorite fruits: apple, banana, orange
Total fruits: 3

多行原始插值字符串

原始插值字符串可以跨越多行,以进行复杂的格式设置。

Program.cs
string name = "Alice";
int score = 95;

string message = $"""
    Dear {name},
    Your score is {score}.
    {(score >= 90 ? "Excellent work!" : "Keep practicing!")}
    """;

Console.WriteLine(message);

该程序使用带有嵌入表达式的多行原始插值字符串来格式化消息。

$ dotnet run
Dear Alice,
Your score is 95.
Excellent work!

来源

C# 中的字符串插值

本教程演示了 C# 中字符串插值的各种技术。

作者

我的名字是 Jan Bodnar,我是一位充满热情的程序员,拥有丰富的编程经验。 我从 2007 年开始撰写编程文章。 至今,我已撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 C# 教程