在 C# 的插值字符串($ 开头的字符串)中,表示大括号需要使用双重大括号:
1. 基本用法
csharp
// 表示单个大括号
string result1 = $"{{"; // 输出: {
string result2 = $"}}"; // 输出: }
string result3 = $"{{}}"; // 输出: {}
// 表示大括号包围的文本
string result4 = $"{{Hello}}"; // 输出: {Hello}
2. 结合插值表达式
csharp
string name = "张三";
int score = 95;
// 正确:输出 {张三的成绩是95}
string message1 = $"{{{name}的成绩是{score}}}";
// 输出 JSON 格式
string json = $"{{ \"name\": \"{name}\", \"score\": {score} }}";
// 输出: { "name": "张三", "score": 95 }
3. 更复杂的例子
csharp
// 输出格式化的大括号内容
for (int i = 1; i <= 3; i++)
{
Console.WriteLine($"{{{i}}}"); // 输出: {1}, {2}, {3}
}
// 输出代码片段
string code = @$"public void Test()
{{
Console.WriteLine(""Hello"");
}}";
// 字符串内同时使用插值和转义大括号
int x = 10, y = 20;
string result = $"和是 {{{x + y}}}"; // 输出: 和是 {30}
4. 注意事项
-
奇数个大括号需要特别注意:
csharp// 错误!会编译错误,因为三个大括号解析有问题 // string error = $"{{{"; // 正确写法 string correct = $"{{{""; // 输出: {{ -
顺序很重要 :从左到右解析,一对
{``{转义为一个{
5. 实际应用场景
csharp
// 生成模板字符串
string template = $"{{{0}}}"; // 可用于 string.Format 的模板
string formatted = string.Format(template, "值"); // 输出: {值}
// 生成 XML/HTML 属性
string value = "test";
string html = $"<div class=\"{value}\">{{content}}</div>";
// 输出: <div class="test">{content}</div>
记住规则 :在插值字符串中,使用 {``{ 表示字面量的 {,}} 表示字面量的 }。