简体   繁体   English

C# 三重双引号(三个双引号)

[英]C# triple double quotes (three double quotes)

What is the purpose of triple douple quotes """ in C#? It seems it is used for multiline text. But why not to use single double quotes? Eg: C#中三重双引号"""的作用是什么?似乎用于多行文本。但为什么不使用单双引号?例如:

string text = """
  some text
  some text
  some text
  """;

I think a simple example can explain better than many a text.我认为一个简单的例子可以比许多文本更好地解释。 Suppose we have a sql query which we want to keep in a good format to be easy readable.假设我们有一个 sql 查询,我们希望保持良好的格式以便于阅读。

If we put it naive, it won't compile:如果我们天真地说,它不会编译:

string sql = 
  "select id, 
          name
     from MyTable"; // <- Doesn't compile 

We can use @ to have verbatim strings which now compiles我们可以使用@来获得现在可以编译的逐字字符串

string sql = 
 @"select id, 
          name
     from MyTable"; 

...

// A little bit different format somewhere else in c# code
string sameSql = @"select id, 
                          name
                     from MyTable"; 

But yet another problem arises: we have different strings and that's why RDBMS will treat them as different queries, both versions will be parsed and optimized, put into cache etc. So we have the same job done several times (and even worse: parsed queries cache can be flooded by same query in different formats and it'll be not enough space for other queries).但是另一个问题出现了:我们有不同的字符串,这就是为什么 RDBMS 将它们视为不同的查询,两个版本都将被解析和优化,放入缓存等。所以我们多次完成相同的工作(甚至更糟:解析查询缓存可能会被不同格式的相同查询淹没,并且没有足够的空间用于其他查询)。

From sql we havesql我们有

select id, 
          name
     from MyTable

From sameSql we have the same query but in a different format:sameSql我们有相同的查询,但格式不同:

select id, 
                          name
                     from MyTable

Note that leading spaces are preserved (we used verbatim strings, right?) and that's a problem.请注意,前导空格被保留(我们使用逐字字符串,对吗?),这是一个问题。

The solution is to use new """ construction解决方案是使用新的"""构造

string sql = 
 """
    select id, 
           name
      from MyTable
 """; 

...

// A little bit different format
string sameSql = """
                    select id, 
                           name
                      from MyTable
                 """; 

In both cases we'll get the same text在这两种情况下,我们都会得到相同的文本

select id, 
       name
  from MyTable

the query will be parsed, optimized and put into cache just once, c# code style ignored .查询将被解析、优化并放入缓存一次, c# 代码风格被忽略

Source: C# 11 Preview Updates – Raw string literals来源: C# 11 预览更新 – 原始字符串文字

If you work with strings literal that contain quotes or embedded language strings like JSON, XML, HTML, SQL, Regex and others, raw literal strings may be your favorite feature of C# 11. Previously if you copied a literal string with quotes into a C# literal, the string ended at the first double quote with compiler errors until you escaped each one.如果您使用包含引号或嵌入语言字符串的字符串文字,例如 JSON、XML、HTML、SQL、正则表达式等,原始文字字符串可能是您最喜欢的 C# 11 功能。字面上,字符串以第一个双引号结尾,并带有编译器错误,直到您对每个双引号进行转义。 Similarly, if you copied text with curly braces into an interpolated string literal, each curly bracket was interpreted as the beginning of a nested code expression unless you escape it, generally by doubling the curly bracket.类似地,如果您将带有大括号的文本复制到一个内插字符串文字中,则每个大括号都被解释为嵌套代码表达式的开头,除非您将其转义,通常是将大括号加倍。

Raw string literals have no escaping. For example, a backslash is output as a backslash, and \t is output as the backslash and a t , not as the tab character.原始字符串文字没有 escaping。例如,反斜杠是 output 作为反斜杠, \t是 output 作为反斜杠和t而不是制表符。

Raw string literals start and end with at least three double quotes ( """...""" ).原始字符串文字以至少三个双引号 ( """...""" ) 开头和结尾。 Within these double quotes, single " are considered content and included in the string. Any number of double quotes less than the number that opened the raw string literal are treated as content. So, in the common case of three double quotes opening the raw string literals, two double quotes appearing together would just be content. If you need to output a sequence of three or more double quotes, just open and close the raw string literal with at least one more quote than that sequence.在这些双引号中,单个"被视为内容并包含在字符串中。任何数量小于打开原始字符串文字的双引号都被视为内容。因此,在打开原始字符串的三个双引号的常见情况下如果您需要 output 一个包含三个或更多双引号的序列,只需打开和关闭原始字符串文字,并且至少比该序列多一个引号。

Raw string literals can be interpolated by preceding them with a $ .可以通过在它们前面加上$来插入原始字符串文字。 The number of $ that prefixes the string is the number of curly brackets that are required to indicate a nested code expression.字符串前面的$的数量是指示嵌套代码表达式所需的大括号的数量。 This means that a $ behaves like the existing string interpolation – a single set of curly brackets indicate nested code.这意味着$的行为类似于现有的字符串插值 - 一组大括号表示嵌套代码。 If a raw string literal is prefixed with $$ , a single curly bracket is treated as content and it takes two curly brackets to indicate nested code.如果原始字符串文字以$$为前缀,则将单个大括号视为内容,并且需要两个大括号来指示嵌套代码。 Just like with quotes, you can add more $ to allow more curly brackets to be treated as content.就像引号一样,您可以添加更多$以允许将更多大括号视为内容。 For example:例如:

 const int veryCold = -30; const int comfortable = 20; string jsonString = $$""" { "TemperatureRanges": { "Cold": { "High": {{comfortable}}, "Low": {{veryCold}} } } } """;

Raw string literals also have new behavior around automatically determining indentation of the content based on leading whitespace.原始字符串文字也有新的行为,可以根据前导空格自动确定内容的缩进。 To learn more about this and to see more examples on this feature, check out the docs article Raw String Literals .要了解有关此功能的更多信息并查看有关此功能的更多示例,请查看文档文章 Raw String Literals

PS Thanks to Roe and ProgrammingLlama for pointing to this articles. PS感谢RoeProgrammingLlama指向这篇文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM