2013-02-12 46 views
7

首先,它並不像groupWhat does the @ symbol before a variable name mean in C#?在c#之前變量意味着什麼?

的複製是不是一個保留關鍵字。

我寫了一些代碼,並且resharper建議我在變量group之前加@

任何想法爲什麼?

var group = GetDefaultGroup(ClientServiceCommon.Poco.Group); 

filteredPairs = @group.Pairs.ToList(); 
+1

是的,它可以讓你使用一個保留(不保留)的關鍵字,但是也可以在_any_變量名之前。爲什麼resharper暗示它是另一個問題,儘管LINQ [group](http://msdn.microsoft.com/en-us/library/bb384063.aspx)子句是一個很好的候選者。 – Oded 2013-02-12 14:32:48

+4

'group'是C#中的上下文關鍵字。參見[MSDN](http://msdn.microsoft.com/zh-cn/library/x53a06bb.aspx) – 2013-02-12 14:33:51

+1

'從filteredPairs組groupOne中的組中獲得'.omething' – 2013-02-12 14:37:37

回答

12

正如你正確地指出,group是不是保留關鍵字(語言設計者儘量不引進新的保留關鍵字時,他們爲了不破壞現有的程序添加新的功能,語言)。 然而,它是一個上下文關鍵字:它成爲LINQ查詢表達式中的關鍵字。 Resharper建議您重新命名有問題的變量,以避免在查詢表達式中使用此變量時產生的歧義。

language specification

7.16.1 Ambiguities in query expressions

Query expressions contain a number of 「contextual keywords」, i.e., identifiers that have special meaning in a given context. Specifically these are from, where, join, on, equals, into, let, orderby, ascending, descending, select, group and by. In order to avoid ambiguities in query expressions caused by mixed use of these identifiers as keywords or simple names, these identifiers are considered keywords when occurring anywhere within a query expression. For this purpose, a query expression is any expression that starts with 「from identifier」 followed by any token except 「;」, 「=」 or 「,」.

如果你想做到以下幾點,你會得到一個編譯錯誤:

var filteredParis = from pair in group.Pairs // group is now treated as a keyword 
        select pair;