c#中@標志的作用


  前言:今日遇到了一個問題:怎么將含有單引號和雙引號的復雜sql放入,string.farmat(@"");  中?   這其中遇到了一個關鍵字@,  我使用@的目的是讓sql語句可以換行寫,但是遇到了里面含有雙引號的問題。

突然忘了怎么該把雙引號給轉義了,使用反斜杠:"\"  不好用,因為有@關鍵字,   在@關鍵字中想轉義雙引號,需要使用一對才行,后台百度查詢了其他道友的文章,記錄下做分享吧:

 

重點:在字符串前加@,字符串中的轉義字符串將不再轉義。例外:""仍將轉義為",{{和}}仍將轉義為{和}。在同時使用字符串內插和逐字字符串時,$要在@的前面

 

道友文章:https://www.cnblogs.com/zhaochenxi/p/10570482.html

 

參考微軟官方文檔-特殊字符@,地址 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