在.NET中使用文本块初始化字符串的语法是什么?

Eve*_*ien 2 .net c# text

我正在编写单元测试,并且不记得使用大块格式化文本初始化字符串的语法.

string _testData = "a couple screens worth of text data here
and I need to preserve the formatting
such as line breaks,
etc.";
Run Code Online (Sandbox Code Playgroud)

Ada*_*son 15

@在文字之前添加一个.

string _testData = @"a couple screens worth of text data here
and I need to preserve the formatting
such as line breaks,
etc.";
Run Code Online (Sandbox Code Playgroud)


Sco*_*vey 10

使用@ literal表示字符串类型.

string _testData = @"a couple screens worth of text data here
and I need to preserve the formatting
such as line breaks,
etc.";
Run Code Online (Sandbox Code Playgroud)

来自MSDN:"逐字字符串文字以@开头,并且也用双引号括起来.逐字字符串的优点是不处理转义序列,这使得它易于编写,例如,完全限定的文件名. @ -quoted字符串中的双引号,加倍."


Jon*_*eet 5

正如其他人所说的那样

    string _testData = @"a couple screens worth of text data here
and I need to preserve the formatting
such as line breaks,
etc.";
Run Code Online (Sandbox Code Playgroud)

这称为逐字字符串文字.另一个影响是反斜杠不再用于转义任何东西 - 这使得它对正则表达式和Windows文件路径很有用.

双引号是通过加倍实现的.例如,获取x"y一个字符串:

string verbatim = @"x""y";
string regular = "x\"y";
Run Code Online (Sandbox Code Playgroud)