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

这是我现在拥有的:

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

我知道PHP

<<<BLOCK

BLOCK;

c#有类似的东西吗?


当前回答

另一个需要注意的问题是在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)

其他回答

添加多行:使用@

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

在中间添加字符串值:使用$

string text ="beer";
string query = $"SELECT foo {text} bar ";

多行字符串中间添加值:使用$@

string text ="Customer";
string query = $@"SELECT foo, bar
FROM {text}Table
WHERE id = 42";

附带说明一下,在c# 6.0中,你现在可以将插值字符串与逐字字符串字面值结合起来:

string camlCondition = $@"
<Where>
    <Contains>
        <FieldRef Name='Resource'/>
        <Value Type='Text'>{(string)parameter}</Value>
    </Contains>
</Where>";

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

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.

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

另一个需要注意的问题是在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)

你可以使用@和""。

        string sourse = @"{
        ""items"":[
        {
            ""itemId"":0,
            ""name"":""item0""
        },
        {
            ""itemId"":1,
            ""name"":""item1""
        }
        ]
    }";