这是c#(或可能是VB.net)的.NET问题,但我试图弄清楚以下声明之间的区别:

string hello = "hello";

vs.

string hello_alias = @"hello";

在控制台上打印没有区别,长度属性是相同的。


当前回答

复制自MSDN:

在编译时,逐字字符串被转换为具有所有相同转义序列的普通字符串。因此,如果在调试器监视窗口中查看逐字字符串,将看到编译器添加的转义字符,而不是源代码中的逐字版本。例如,逐字字符串@"C:\files.txt"将以"C:\\files.txt"的形式出现在监视窗口中。

其他回答

将@放在字符串前面可以使用特殊字符,如反斜杠或双引号,而不必使用特殊代码或转义字符。

所以你可以这样写:

string path = @"C:\My path\";

而不是:

string path = "C:\\My path\\";

它是一个逐字串字面量。这意味着转义没有被应用。例如:

string verbatim = @"foo\bar";
string regular = "foo\\bar";

这里逐字和逐字具有相同的内容。

它还允许多行内容——这对SQL来说非常方便:

string select = @"
SELECT Foo
FROM Bar
WHERE Name='Baz'";

对于逐字串字面量来说,一个必要的转义是获得一个双引号("),你可以通过将它加倍来做到:

string verbatim = @"He said, ""Would you like some coffee?"" and left.";
string regular = "He said, \"Would you like some coffee?\" and left.";

复制自MSDN:

在编译时,逐字字符串被转换为具有所有相同转义序列的普通字符串。因此,如果在调试器监视窗口中查看逐字字符串,将看到编译器添加的转义字符,而不是源代码中的逐字版本。例如,逐字字符串@"C:\files.txt"将以"C:\\files.txt"的形式出现在监视窗口中。

http://msdn.microsoft.com/en-us/library/aa691090.aspx

c#支持两种形式的字符串字面量:常规字符串字面量和逐字字符串字面量。

常规字符串文字由0个或多个用双引号括起来的字符组成,如"hello",并且可能包括简单转义序列(如制表符的\t)和十六进制和Unicode转义序列。

A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.

这是一个逐字字符串,并更改转义规则-现在唯一被转义的字符是“,转义为“”。这对于文件路径和regex特别有用:

var path = @"c:\some\location";
var tsql = @"SELECT *
            FROM FOO
            WHERE Bar = 1";
var escaped = @"a "" b";

etc