$ - 字符串內插
$ 特殊字符將字符串文本標識為內插字符串 。 內插字符串是可能包含內插表達式的字符串文本 。 將內插字符串解析為結果字符串時,帶有內插表達式的項會替換為表達式結果的字符串表示形式。 從 C# 6 開始可以使用此功能。
若要將字符串標識為內插字符串,可在該字符串前面加上 $ 符號。 字符串文本開頭的 $ 和 " 之間不能有任何空格。
舉例:
string name = "Mark"; var date = DateTime.Now; // Composite formatting: Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date); // String interpolation: Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now."); // Both calls produce the same output that is similar to: // Hello, Mark! Today is Wednesday, it's 19:40 now.
@ - 逐字字符串標識符
@ 特殊字符用作原義標識符。 它具有以下用途:
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:\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])或短名稱(例如 [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() { } }
【轉載】:https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/tokens/
