Possible Duplicate:
W开发者_StackOverflow社区hat's the use/meaning of the @ character in variable names in C#?
I was doing some .net development and I noticed I could add an @ symbol before any method call, i.e.:
var message = dog.@SayHello();
Just wondering, why is the reason this can be done ??
The @
symbol can escape keywords and turn them into ordinary identifiers. Most .net languages support a mechanism like this since keywords are language dependent, and thus code written in other languages might collide with a keyword in your language without even noticing it.
Some people like using @this
for the first parameter extension methods.
public static void MyExtension(this MyType @this)
another scenario where this can be useful is when using members to represent html attributes. Then without this feature you could not represent the class
attribute.
An @
symbol can be pre-fixed to any identifier in case you're interoperating with code written in another language that uses C# keywords as identifiers:
object @class; //allowed
object class; //error
This is simply part of the definition of a valid identifier in C#.
@
lets you use an identifier that would otherwise be interpreted as a keyword.
For example, if you want to have a variable named class, you can write this:
int @class;
Of course, because you can do it doesn't mean it's a good idea to do it.
Some situations where it's useful is code generators that create C# code from a template or external source. e.g. xsd.exe
is an SDK command-line tool creates C# classes that back up an XML schema. If your XML schema contains an element or attribute name that is reserved in C# (such as class), xsd.exe
would preserve the name in the matching C# class but it would prefix it with a @
.
It's a case of just because we can, doesn't mean we should.
精彩评论