逐字文本 - @ 变量、属性和字符串文本

特殊 @ 字符用作逐字标识符。 可通过以下方式使用它:

  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. 其类型名称通常包括后缀 特性,尽管编译器不强制实施此约定。 然后,可以通过其全类型名称(例如,[InfoAttribute]或其缩短的名称)在代码中引用该属性。 [Info] 但是,如果两个缩短的属性类型名称相同,并且一个类型名称包含 属性 后缀,但另一个类型名称不相同,则会发生命名冲突。 例如,以下代码无法编译,因为编译器无法确定该或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()
       {
       }
    }
    

另请参阅