可能重複:
What's the use/meaning of the @ character in variable names in C#?什麼是C#的語法@
我已經在好幾個地方,包括ReSharper的轉換代碼看到...
SomeClass @object = new SomeClass(...);
我想它是匿名的,但我認爲我錯了
這是否真的意味着什麼?
可能重複:
What's the use/meaning of the @ character in variable names in C#?什麼是C#的語法@
我已經在好幾個地方,包括ReSharper的轉換代碼看到...
SomeClass @object = new SomeClass(...);
我想它是匿名的,但我認爲我錯了
這是否真的意味着什麼?
前綴「@」允許使用關鍵字作爲標識符,當與其他編程語言進行接口時,該標識符是 有用的。 字符@實際上並不是標識符的一部分,因此標識符 可能在其他語言中被看作是普通標識符,而不包含前綴 。帶有@前綴的標識符稱爲逐字 標識符。
例子:
class @class
{
public static void @static(bool @bool) {
if (@bool)
System.Console.WriteLine("true");
else
System.Console.WriteLine("false");
}
}
它允許您使用保留關鍵字作爲標識符。例如,我遇到的一個常見場景是定義鎖定對象,例如
object lock = new object(); // this would throw a compiler error as `lock` is a reserved word.
所以我與@
符號前綴它告訴編譯器這不是一個類型,但文字:
object @lock = new object();
在一個側面說明,它通常是一個很好的指標,你如果您遇到類似衝突,那麼您的識別符的描述性不夠。
它表示「文字」,即「這個名稱不是關鍵字或類型標識符」。沒有它,object
將被視爲一種類型。
背後的原因是該對象是C#中的受保護關鍵字。 @符號會告訴編譯器這應該是變量的名稱,不應與object
關鍵字混淆。
見我的答案在this question。
@
符號允許您在變量名中使用reserved words。
int @class = 1;
void MyMethod(int @goto);
bool @public { get; set; }
關鍵詞預定義保留標識符具有特殊意義的編譯器。除非它們包含@
作爲前綴,否則它們不能用作程序中的標識符。例如,@if
是合法標識符,但是如果不是因爲它是關鍵字。
請參閱本C# Keywords
能否請你舉一個例子,我不明白我 – guyl