关于C#:为什么我们要用@with””替换为另一个字符串?

Why do we use @ with “” while trying to replace it with another string

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
What's the @ in front of a string in C#?

为什么我们用@来代替\,用另一个字符串来代替string.replace(@"\","$$")我正在使用C#Windows应用程序


字符串文字前面的@使其成为逐字字符串文字,因此反斜杠\不需要翻倍。您可以使用"\\"而不是@"\"来达到同样的效果。


因为如果你不这样做,你就必须用\\逃离\

@用于所谓的逐字字符串


在C中,可以在字符串前面加上@使其逐字,因此不需要转义特殊字符。

1
@""

相同

1
"\"

C语言规范2.4.4.5字符串文字说明:

C# supports two forms of string literals: regular string literals and
verbatim string literals.

A regular string literal consists of zero or more characters enclosed
in double quotes, as in"hello", and may include both simple escape
sequences (such as \t for the tab character), and hexadecimal and
Unicode escape sequences.

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.

使用@字符的逐字字符串文字,使您在实际中更容易转义几乎所有字符,否则您将不得不在字符串中单独转义\字符。

注意:即使使用逐字模式,"字符仍需要转义。

所以我会用它来节省时间,不必通过一个长字符串来转义所有需要转义的字符。


因为反斜杠被视为转义符,如果不使用"@",则会出现"未识别转义序列"错误。使用"@"会告诉编译器忽略转义字符。这可能会有所帮助。