在 C# 中,如何使 $““ 字符串支持换行

在 C# 中,如何使 $"" 字符串支持换行

在 C# 中,使用 $"" 字符串(字符串插值)时支持换行有几种方式:

1. 直接换行(自动拼接)

csharp 复制代码
string message = $"Hello, {name}!" +
                $"This is a multi-line " +
                $"string with interpolation.";

2. 使用 @ 符号(逐字字符串)

csharp 复制代码
string message = $@"Hello, {name}!
This is a multi-line string
with interpolation and line breaks.";

3. 组合使用 @或@@ 或 @@或@

csharp 复制代码
// 两种写法都可以
string message1 = $@"Line 1: {variable1}
Line 2: {variable2}";

string message2 = @$"Line 1: {variable1}
Line 2: {variable2}";

4. 使用 StringBuilder 或环境换行符

csharp 复制代码
string message = $"Line 1: {variable1}{Environment.NewLine}" +
                 $"Line 2: {variable2}";

// 或者使用 \r\n
string message = $"Line 1: {variable1}\r\n" +
                 $"Line 2: {variable2}";

示例代码

csharp 复制代码
string name = "张三";
int age = 25;

// 方法1:直接换行
string message1 = $"姓名: {name}" +
                  $"年龄: {age}";

// 方法2:使用逐字字符串
string message2 = $@"姓名: {name}
年龄: {age}
这是多行文本";

// 方法3:环境换行符
string message3 = $"姓名: {name}{Environment.NewLine}年龄: {age}";

Console.WriteLine(message2);

输出结果:

复制代码
姓名: 张三
年龄: 25
这是多行文本

注意事项

  • $@@$ 是等价的,推荐使用 $@(更常见)
  • 逐字字符串会保留所有空白字符,包括换行和缩进
  • 如果需要在字符串中包含引号,使用两个引号 "" 来转义

选择哪种方式取决于你的具体需求和个人编码风格偏好。

相关推荐
李树健12311 小时前
.NET 10 & C# 14 New Features 新增功能介绍-ASP.NET Core
c#·asp.net·.net
无风听海11 小时前
.NET10之IHostedService深度解析
c#·.net
asdzx6712 小时前
使用 C# 将 Excel 转换成高质量 JPG
开发语言·c#·excel
CSharp精选营12 小时前
.NET被上海信创“拉黑”了?刚子给你讲明白:别慌,这事儿没那么严重
c#·.net·信创
周杰伦fans2 天前
C# required 关键字详解
开发语言·网络·c#
游乐码2 天前
c#ArrayList
开发语言·c#
唐青枫2 天前
C#.NET Monitor 与 Mutex 深入解析:进程内同步、跨进程互斥与使用边界
c#·.net
周杰伦fans2 天前
cad文件选项卡不见了怎么办?
c#
llm大模型算法工程师weng2 天前
Python敏感词检测方案详解
开发语言·python·c#
游乐码2 天前
c#stack
开发语言·c#