zoukankan      html  css  js  c++  java
  • C#的@标志的使用情况—本篇blog采用Markdown编写

    @(C# 参考--出自官方文档入口

    1.使 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!
    

    2.指示将原义解释字符串。 @ 字符在此实例中定义原义标识符。 简单转义序列(如代表反斜杠的 "")、十六进制转义序列(如代表大写字母 A 的 "x0041")和 Unicode 转义序列 (如代表大写字母 A 的 "u0041")都将按字面解释。 只有引号转义序列 ("") 不会按字面解释;因为它生成单引号。 此外,如果是逐字内插字符串,大括号转义序列({{ 和 }})不按字面解释;它们会生成单个大括号字符。 下面的示例分别使用常规字符串和原义字符串定义两个相同的文件路径。 这是原义字符串的较常见用法之一。

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

    下面的示例演示定义包含相同字符序列的常规字符串和原义字符串的效果。

    string s1 = "He said, "This is the last u0063hancex0021"";
    string s2 = @"He said, ""This is the last u0063hancex0021""";
    
    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 u0063hancex0021"  
    

    3.使编译器在命名冲突的情况下区分两种属性。 属性是派生自 Attribute 的类。 其类型名称通常包含后缀 Attribute,但编译器不会强制进行此转换。 随后可在代码中按其完整类型名称(例如 [InfoAttribute])或短名称(例如 [Info])引用此属性。 但是,如果两个短名称相同,并且一个类型名称包含 Attribute 后缀而另一类型名称不包含,则会出现命名冲突。 例如,由于编译器无法确定将 Info 还是 InfoAttribute 属性应用于 Example 类,因此下面的代码无法编译。

    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'. Specify the full name 'InfoAttribute' to select it.
    public class Example
    {
       [InfoAttribute("The entry point.")]
       public static void Main()
       {
       }
    }
    
  • 相关阅读:
    offset家族
    $的符号封装
    操作字符串
    无缝滚动
    根据字符返回位置
    网页编码和解码
    小米手机案例
    字符串对象常用方法
    匀速运动案例
    Render Functions & JSX
  • 原文地址:https://www.cnblogs.com/ubantu/p/11253835.html
Copyright © 2011-2022 走看看