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

Sun*_*Lim 9 c# string

请考虑以下行:

readonly private string TARGET_BTN_IMG_URL = @"\\ad1-sunglim\Test\";
Run Code Online (Sandbox Code Playgroud)

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

Mik*_*keP 17

它表示文字字符串,其中'\'字符不表示转义序列.


Bil*_*eal 9

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

string s = "C:\Windows\Myfile.txt";
Run Code Online (Sandbox Code Playgroud)

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

string s = "C:\\Windows\\Myfile.txt";
Run Code Online (Sandbox Code Playgroud)

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

string s = @"C:\Windows\Myfile.txt";
Run Code Online (Sandbox Code Playgroud)

完全没问题.


编辑: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";
Run Code Online (Sandbox Code Playgroud)