代码之家  ›  专栏  ›  技术社区  ›  Sungguk Lim

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

  •  9
  • Sungguk Lim  · 技术社区  · 15 年前

    考虑以下行:

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

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

    3 回复  |  直到 15 年前
        1
  •  17
  •   MikeP    15 年前

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

        2
  •  8
  •   Billy ONeal IS4    15 年前

    @告诉C将其视为 文字串 verbatim string literal . 例如:

    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";
    
        3
  •  2
  •   Nnp    15 年前

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