[学习日记] - C# 逐字字符串标识符, @符号的几个用法

340 阅读1分钟

1. 使用 C# 关键字作为命名

public void OutputString(string @params)
{
    Console.WriteLine(@parmas);
}

OutputString("好家伙, 电饭煲自己打开了.");

2. 原义解释字符串

pubilc void Example()
{
    var filename1 = @"c:\users\tiehanhan\u6de6.txt";
    var filename2 = "c:\\users\\tiehanhan\\u6de6.txt";
    Console.WriteLine(filename1);
    Console.WriteLine(filename2);
    
    // 输出内容:
    //      c:\users\tiehanhan\u6de6.txt
    //      c:\users\tiehanhan\u6de6.txt
    
    /***********************************/

    var @string = "歪比巴卜 \"我觉得很\u6de6\"!";
    var string1 = @"歪比巴卜 ""我觉得很\u6de6""!";
    Console.WriteLine(@string);
    Console.WriteLine(string1);
    
    // 输出内容:
    //      歪比巴卜 "我觉得很淦"!
    //      歪比巴卜 "我觉得很\u6de6"!
}

3. 在编译器命名冲突的情况下区分使用哪个属性

  • => 表达式主体定义
  • Attribute 特性类
using System;

public class Info : Attribute
{
    private string information;
    
    public Info(string info)
        => information = info;
}

public class InfoAttribute : Attribute
{
    private string information;
    
    public InfoAttribute(string info)
        => information = info;
}

// [Info("例子")]
//      “Info”在“Info”和“InfoAttribute”之间不明确
public class Example
{
    [@Info("哈喽哇, Main")] // 正常
    public static void Main(string[] args)
    {
    }
    
    [InfoAttribute("哈喽哇, Output")] // 正常
    public static void Output(string value)
    {
    }
}