C#中的關鍵字@
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()
{
}
}

浙公網安備 33010602011771號