$ - 字符串内插
从 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.
@ - 逐字字符串标识符
它具有以下用途:
下面的示例使用 @ 字符定义其在 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、这是原义字符串的较常见用法之一。
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、例如,由于编译器无法确定将 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/