$和@的用法

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

$和@的⽤法
$ - 字符串内插
$特殊字符将字符串⽂本标识为内插字符串。

内插字符串是可能包含内插表达式的字符串⽂本。

将内插字符串解析为结果字符串时,带有内插表达式的项会替换为表达式结果的字符串表⽰形式。

从 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,但编译器不会强制进⾏此转换。

随后可在代码中按其完整类型名称(例如[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()
{
}
}。

相关文档
最新文档