`@`在C#中的字符串开头是什么意思?

请考虑以下行:

readonly private string TARGET_BTN_IMG_URL = @"\\ad1-sunglim\Test\"; 

在这一行中,为什么需要附加@?

它表示一个文字字符串,其中’\’字符不表示转义序列。

@告诉C#将其视为文字字符串 逐字字符串文字 。 例如:

 string s = "C:\Windows\Myfile.txt"; 

是一个错误,因为\W\M不是有效的转义序列。 你需要这样写它:

 string s = "C:\\Windows\\Myfile.txt"; 

为了更清楚,您可以使用文字字符串,它不能将\识别为特殊字符。 因此:

 string s = @"C:\Windows\Myfile.txt"; 

完全没问题。


编辑: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"; 

因为你的字符串包含转义序列“\”。 为了告诉编译器不要将“\”视为转义序列,你必须使用“@”。