这几天看C# 11的新语法,学习到了Raw string literals
今天给大家分享一下:
原始字符串是字符串的一种新格式。
原始字符串可以包含任意文本,包括空格、新行、嵌入引号和其他特殊字符,无需转义字符(这个很关键、也很简单)。
原始字符串以至少三个双引号 (""") 字符开头。 它以相同数量的双引号字符结尾。
通常,原始字符串在单个行上使用三个双引号来开始字符串,在另一行上用三个双引号来结束字符串。 左引号之后、右引号之前的换行符不包括在最终内容中:
写个示例代码看看
先新建了一个.NET 7.0的Console应用
- PS E:\Learn\.NET7> dotnet new console --framework net7.0

我们在Program.cs中新增以下代码
- // See https://aka.ms/new-console-template for more information
- Console.WriteLine("Hello, C#11!");
- string txt = """
- This is a long message.
- It has several lines.
- Some are indented
- more than others.
- Some should start at the first column.
- Some have "quoted text" in them.
- """;
- Console.WriteLine(txt);
dotnet run运行

大家可以看到,声明的原始字符串txt,可以按照输入的格式全量输出。
右双引号左侧的任何空格都将从字符串中删除。
原始字符串可以与字符串内插结合使用,以在输出文本中包含大括号。 多个 $
字符表示有多少个连续的大括号开始和结束内插:
- var Longitude= """12""";
- var Latitude= """16""";
- var location = $$"""
- You are at {{{Longitude}}, {{Latitude}}}
- """;
- Console.WriteLine(location);
猜猜输出什么:
You are at {12, 16}
前面的示例指定了两个大括号开始和结束内插。 第三个重复的左大括号和右大括号包括在输出字符串中。
周国庆
2022/12/11