[英]What does `@` mean at the start of a string in C#?
Consider the following line: 请考虑以下行:
readonly private string TARGET_BTN_IMG_URL = @"\\ad1-sunglim\Test\";
In this line, why does @ need to be attached? 在这一行中,为什么需要附加@?
它表示文字字符串,其中'\\'字符不表示转义序列。
@ tells C# to treat that as a literal string verbatim string literal . @告诉C#将其视为
文字字符串 逐字字符串文字 。 For example: 例如:
string s = "C:\Windows\Myfile.txt";
is an error because \\W
and \\M
are not valid escape sequences. 是一个错误,因为
\\W
和\\M
不是有效的转义序列。 You need to write it this way instead: 你需要这样写它:
string s = "C:\\Windows\\Myfile.txt";
To make it clearer, you can use a literal string, which does not recognize \\ as a special character. 为了更清楚,您可以使用文字字符串,它不会将\\识别为特殊字符。 Hence:
因此:
string s = @"C:\Windows\Myfile.txt";
is perfectly okay. 完全没问题。
EDIT: MSDN provides these examples: 编辑:MSDN提供以下示例:
string a = "hello, world"; // hello, world
string b = @"hello, world"; // hello, world
string c = "hello \t world"; // hello world
string d = @"hello \t world"; // hello \t world
string e = "Joe said \"Hello\" to me"; // Joe said "Hello" to me
string f = @"Joe said ""Hello"" to me"; // Joe said "Hello" to me
string g = "\\\\server\\share\\file.txt"; // \\server\share\file.txt
string h = @"\\server\share\file.txt"; // \\server\share\file.txt
string i = "one\r\ntwo\r\nthree";
string j = @"one
two
three";
because you string contains escape sequence "\\". 因为你的字符串包含转义序列“\\”。 in order to tell compiler not to treat "\\" as escape sequence you have to use "@".
为了告诉编译器不要将“\\”视为转义序列,你必须使用“@”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.