C#11新特性-Raw string literals原始字符串研究、示例

这几天看C# 11的新语法,学习到了 Raw string literals

今天给大家分享一下:

原始字符串是字符串的一种新格式。

原始字符串可以包含任意文本,包括空格、新行、嵌入引号和其他特殊字符, 无需转义字符(这个很关键、也很简单)

原始字符串以至少 三个双引号 (“””)字符开头。 它以相同数量的双引号字符结尾。

通常,原始字符串在单个行上使用三个双引号来开始字符串,在另一行上用三个双引号来结束字符串。 左引号之后、右引号之前的换行符不包括在最终内容中:

写个示例代码看看

先新建了一个.NET 7.0的Console应用

bash;gutter:true; PS E:\Learn.NET7> dotnet new console --framework net7.0</p> <pre><code> ![C#11新特性-Raw string literals原始字符串研究、示例](https://johngo-pic.oss-cn-beijing.aliyuncs.com/articles/20230809/23525-20221211213211112-1527193758.png) 我们在Program.cs中新增以下代码 </code></pre> <p>// See https://aka.ms/new-console-template for more information Console.WriteLine("Hello, C#11!"); string txt = """ This is a long message.</p> <pre><code>It has several lines. Some are indented more than others. Some should start at the first column. Some have "quoted text" in them. """; </code></pre> <p>Console.WriteLine(txt);</p> <pre><code> dotnet run运行 ![C#11新特性-Raw string literals原始字符串研究、示例](https://johngo-pic.oss-cn-beijing.aliyuncs.com/articles/20230809/23525-20221211213409562-1455520266.png) 大家可以看到,声明的原始字符串txt,可以按照输入的格式全量输出。 右双引号左侧的任何空格都将从字符串中删除。 原始字符串可以与字符串内插结合使用,以在输出文本中包含大括号。 多个 $ 字符表示有多少个连续的大括号开始和结束内插: </code></pre> <p>var Longitude= """12"""; var Latitude= """16"""; var location = $$""" You are at {{{Longitude}}, {{Latitude}}} """; Console.WriteLine(location);

猜猜输出什么:

You are at {12, 16}

前面的示例指定了两个大括号开始和结束内插。 第三个重复的左大括号和右大括号包括在输出字符串中。

周国庆

2022/12/11

Original: https://www.cnblogs.com/tianqing/p/16974572.html
Author: Eric zhou
Title: C#11新特性-Raw string literals原始字符串研究、示例

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/796798/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球