共用方式為


逐字文字 - @ 變數、屬性和字串常值

@特殊字元會做為逐字標識碼。 您可以透過下列方式使用它:

  1. 若要指出字串常值是逐字解譯。 @這個實例中的字元會定義逐字字串常值。 簡單的逸出序列(例如 "\\" 反斜杠)、十六進位逸出序列(例如 "\x0041" 大寫 A),以及 Unicode 逸出序列(例如 "\u0041" 大寫 A)會以字面方式解譯。 只有引號逸出序列 ("") 不會以字面方式解譯;它會產生一個雙引號。 此外,如果逐字 插入字串 大括號逸出序列 ({{}}) 不會以字面方式解譯;它們會產生單一大括號字元。 下列範例會定義兩個相同的檔案路徑,一個是使用一般字串常值,另一個是使用逐字字串常值。 這是逐字字串常值最常見的用法之一。

    string filename1 = @"c:\documents\files\u0066.txt";
    string filename2 = "c:\\documents\\files\\u0066.txt";
    
    Console.WriteLine(filename1);
    Console.WriteLine(filename2);
    // The example displays the following output:
    //     c:\documents\files\u0066.txt
    //     c:\documents\files\u0066.txt
    

    下列範例說明定義一般字串常值和包含相同字元序列的逐字字串常值的效果。

    string s1 = "He said, \"This is the last \u0063hance\x0021\"";
    string s2 = @"He said, ""This is the last \u0063hance\x0021""";
    
    Console.WriteLine(s1);
    Console.WriteLine(s2);
    // The example displays the following output:
    //     He said, "This is the last chance!"
    //     He said, "This is the last \u0063hance\x0021"
    
  2. 若要使用 C# 關鍵詞作為標識碼。 字元會 @ 前置詞編譯程式要解譯為標識元而非 C# 關鍵詞的程式代碼專案。 下列範例會 @ 使用 字元來定義它在 for 迴圈中使用的 for 標識碼。

    string[] @for = { "John", "James", "Joan", "Jamie" };
    for (int ctr = 0; ctr < @for.Length; ctr++)
    {
       Console.WriteLine($"Here is your gift, {@for[ctr]}!");
    }
    // The example displays the following output:
    //     Here is your gift, John!
    //     Here is your gift, James!
    //     Here is your gift, Joan!
    //     Here is your gift, Jamie!
    
  3. 若要讓編譯程式在命名衝突的情況下區分屬性。 屬性是衍生自 Attribute的類別。 其類型名稱通常包含後綴 Attribute,不過編譯程式不會強制執行此慣例。 然後,屬性可以透過其完整型別名稱在程式碼中參考 (例如, [InfoAttribute] 或其縮短的名稱 ,例如 , [Info]。 不過,如果兩個縮短的屬性類型名稱相同,且一個類型名稱包含 Attribute 後綴,但另一個則不會發生命名衝突。 例如,下列程式代碼無法編譯,因為編譯程式無法判斷 或 InfoAttribute 屬性是否Info套用至 Example 類別。 如需詳細資訊,請參閱 CS1614

    using System;
    
    [AttributeUsage(AttributeTargets.Class)]
    public class Info : Attribute
    {
       private string information;
    
       public Info(string info)
       {
          information = info;
       }
    }
    
    [AttributeUsage(AttributeTargets.Method)]
    public class InfoAttribute : Attribute
    {
       private string information;
    
       public InfoAttribute(string info)
       {
          information = info;
       }
    }
    
    [Info("A simple executable.")] // Generates compiler error CS1614. Ambiguous Info and InfoAttribute.
    // Prepend '@' to select 'Info' ([@Info("A simple executable.")]). Specify the full name 'InfoAttribute' to select it.
    public class Example
    {
       [InfoAttribute("The entry point.")]
       public static void Main()
       {
       }
    }
    

另請參閱