c#中@標志的作用


參考微軟官方文檔-特殊字符@,地址 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/tokens/verbatim

1、在變量名前加@,可以告訴編譯器,@后的就是變量名。主要用於變量名和C#關鍵字重復時使用。

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、在字符串前加@,字符串中的轉義字符串將不再轉義。例外:""仍將轉義為",{{和}}仍將轉義為{和}。在同時使用字符串內插和逐字字符串時,$要在@的前面

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

3、類似於第一條,用於在命名沖突時區分兩個特性名。特性Attribute自定義的類型名稱在起名時應以Attribute結尾,例如InfoAttribute,之后我們可以用InfoAttribute或Info來引用它。但是如果我們定義了兩個自定義特性,分別命名Info和InfoAttribute,則在使用Info這個名字時,編譯器就不知道是哪個了。這時,如果想用Info,就用@Info,想用InfoAttribute,就把名字寫全。

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()
   {
   }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM