Maui Blazor 中文社区 QQ群:645660665

C# 11 原始字符串文本

原始字符串文本

从 C# 11 开始,可以使用原始字符串字面量更轻松地创建多行字符串,或使用需要转义序列的任何字符。 原始字符串字面量无需使用转义序列。 你可以编写字符串,包括空格格式,以及你希望在输出中显示该字符串的方式。 原始字符串字面量:

以至少三个双引号字符序列 (""") 开头和结尾。 可以使用三个以上的连续字符开始和结束序列,以支持包含三个(或更多)重复引号字符的字符串字面量。
单行原始字符串字面量需要左引号和右引号字符位于同一行上。
多行原始字符串字面量需要左引号和右引号字符位于各自的行上。
在多行原始字符串字面量中,会删除右引号左侧的任何空格。

使用带引号的字符串字面量或逐字字符串字面量时,如果生成的文本包括需要转义序列的字符,应考虑原始字符串字面量。 原始字符串字面量将更易于你和其他人阅读,因为它更类似于输出文本。 例如,请考虑包含格式化 JSON 字符串的以下代码:

string jsonString = """
{
  "Date": "2019-08-01T00:00:00-07:00",
  "TemperatureCelsius": 25,
  "Summary": "Hot",
  "DatesAvailable": [
    "2019-08-01T00:00:00-07:00",
    "2019-08-02T00:00:00-07:00"
  ],
  "TemperatureRanges": {
    "Cold": {
      "High": 20,
      "Low": -10
    },
    "Hot": {
      "High": 60,
      "Low": 20
    }
            },
  "SummaryWords": [
    "Cool",
    "Windy",
    "Humid"
  ]
}
""";
string singleLine = """Friends say "hello" as they pass by.""";
string multiLine = """
    "Hello World!" is typically the first program someone writes.
    """;
string embeddedXML = """
       <element attr = "content">
           <body style="normal">
               Here is the main text
           </body>
           <footer>
               Excerpts from "An amazing story"
           </footer>
       </element >
       """;
// The line "<element attr = "content">" starts in the first column.
// All whitespace left of that column is removed from the string.

string rawStringLiteralDelimiter = """"
    Raw string literals are delimited 
    by a string of at least three double quotes,
    like this: """
    """";
posted @ 2023-09-02 12:58  AlexChow  阅读(89)  评论(0编辑  收藏  举报