c#中@標誌的做用

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

忽然忘了怎麼該把雙引號給轉義了,使用反斜槓:"\"  很差用,由於有@關鍵字,   在@關鍵字中想轉義雙引號,須要使用一對才行,後臺百度查詢了其餘道友的文章,記錄下作分享吧:sql

 

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

 

道友文章:http://www.javashuo.com/article/p-tjwbkayf-ez.htmlcode

 

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

一、在變量名前加@,能夠告訴編譯器,@後的就是變量名。主要用於變量名和C#關鍵字重複時使用。htm

複製代碼
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!
複製代碼

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

複製代碼
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
複製代碼

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

複製代碼
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()
   {
   }
}
複製代碼
相關文章
相關標籤/搜索