C#中的@关键字
@
作为C#中的特殊字符,在Microsoft文档中定义为Verbatim文本
Verbatim的解释为完全一致或者逐字逐句,例如verbatim 地引用了一段文字:
“The researcher stated verbatim: ‘The results indicate a significant correlation between variables.’”
有三种主要的应用场景
1.定义Verbatim字符串文本
string filename1 = @"c:\documents\files\u0066.txt";
string filename2 = "c:\\documents\\files\\u0066.txt";Console.WriteLine(filename1);
Console.WriteLine(filename2);
//输出结果:
// c:\documents\files\u0066.txt
// c:\documents\files\u0066.txt
注意:
- 使用插值字符串时,
{
和}
会优先被$
解析
string s = "World";
Console.WriteLine($@"Hello, {s}!");
//输出结果
//Hello, World!
不使用$
:
string s = "World";
Console.WriteLine(@"Hello, {s}!");
//输出结果
//Hello, {s}!
- 在Verbatim字符串使用
"
,需要使用两个引号,单个使用会解释为字符串结束
string s1 = "He said, \"This is the last \u0063hance\x0021\"";
string s2 = @"He said, ""This is the last \u0063hance\x0021""";Console.WriteLine(s1);
Console.WriteLine(s2);
// 输出结果:
// He said, "This is the last chance!"
// He said, "This is the last \u0063hance\x0021"
2.使用C#中的同名关键字作为标识符
例如,使用for
作为数组名称
string[] @for = { "John", "James", "Joan", "Jamie" };
for (int ctr = 0; ctr < @for.Length; ctr++)
{Console.WriteLine($"Here is your gift, {@for[ctr]}!");
}
//输出结果:
// Here is your gift, John!
// Here is your gift, James!
// Here is your gift, Joan!
// Here is your gift, Jamie!
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.")] // 编译错误CS1614. Ambiguous Info and InfoAttribute.
//正确写法:使用Info属性 [@Info("A simple executable.")] .使用InfoAttribute属性 [@Info("A simple executable.")]
public class Example
{[InfoAttribute("The entry point.")]public static void Main(){}
}