有一个简单的方法来创建一个多行字符串文字在c# ?

这是我现在拥有的:

string query = "SELECT foo, bar"
+ " FROM table"
+ " WHERE id = 42";

我知道PHP

<<<BLOCK

BLOCK;

c#有类似的东西吗?


当前回答

你可以在字符串前面使用@符号来形成一个逐字逐句的字符串字面量:

string query = @"SELECT foo, bar
FROM table
WHERE id = 42";

使用此方法时,您也不必转义特殊字符,除了Jon Skeet的回答中所示的双引号。

其他回答

在c# 11[2022]中,您将能够使用原始字符串字面量。 Raw String Literals的使用使得使用“字符”更容易,而不必编写转义序列。

OP的解决方案:

string query1 = """
    SELECT foo, bar
    FROM table
    WHERE id = 42
    """;

string query2 = """
    SELECT foo, bar
    FROM table
    WHERE id = 42
    and name = 'zoo'
    and type = 'oversized "jumbo" grand'
    """;

更多关于原始字符串字面量的细节

参见原始字符串字面量GitHub问题的全部细节;和博客文章c# 11预览更新-原始字符串文字,UTF-8和更多!

另一个需要注意的问题是在string. format中使用字符串字面值。在这种情况下,你需要转义大括号/方括号'{'和'}'。

// this would give a format exception
string.Format(@"<script> function test(x) 
      { return x * {0} } </script>", aMagicValue)
// this contrived example would work
string.Format(@"<script> function test(x) 
      {{ return x * {0} }} </script>", aMagicValue)

我发现使用字符串文字的问题是,它会让你的代码看起来有点“奇怪”,因为为了在字符串本身中不获得空格,它必须完全左对齐:

    var someString = @"The
quick
brown
fox...";

讨厌的东西。

因此,我喜欢使用的解决方案是:

var someString = String.Join(
    Environment.NewLine,
    "The",
    "quick",
    "brown",
    "fox...");

当然,如果您只是想在逻辑上拆分SQL语句的行,而实际上并不需要新的行,那么您总是可以替换Environment。换行" "。

using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {
         string str = @"Welcome User,
         Kindly wait for the image to
         load";

         Console.WriteLine(str);
      }
   }
}

输出

Welcome User,
Kindly wait for the image to
load

如果你不想要空格/换行,字符串加法似乎可以工作:

var myString = String.Format(
  "hello " + 
  "world" +
  " i am {0}" +
  " and I like {1}.",
  animalType,
  animalPreferenceType
);
// hello world i am a pony and I like other ponies.

如果你愿意,你可以在这里运行上面的程序。