开发者

What does '@' char mean before parameter name in method declaration? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Du开发者_如何学编程plicates:

What does the @ symbol before a variable name mean in C#?

What's the use/meaning of the @ character in variable names in C#?

Hi,

I have one quick question. What does '@' char mean before parameter name in method declaration? Like following:

protected void Method1(Type1 @arg1, Type2 arg2)
...

I use c# with .net 3.5.

Thanks.


It allows reserved words to be used as identifiers. It is usually used by code generators which may be using source names from systems with different keywords than the target language e.g. table names and sproc argument names.


It is a way of escaping an identifier.

E.g. the following two are equivalent:

protected void Method1(Type1 @arg1, Type2 arg2)
protected void Method1(Type1 arg1, Type2 arg2)

@ is only really usefull if you need to name an identifier after a keyword. The below would not compile without the @:

protected void Method1(Type1 @class, Type2 arg2)


For your specific example, it has no meaning. In C#, the @ symbol is used to escape keywords so that they can be used as variable names.

For instance, the following would generate a compiler error:

public void Test(string class){...}

But if you escape with @, it is fine:

public void Test(string @class){...}


It is used to have reserved words as parameters. Example:

string @string = "abc";

or:

string @class = "foo";

arg1 is not a reserved word so using @ is not necessary. This being said, using reserved words to name your parameters is not a good idea. There are cases though where this is useful. For example in ASP.NET MVC some HTML extension methods take an anonymous object as parameter to emit html attributes. So you have syntax like this:

<%= Html.ActionLink("text", "action", "controller", null, new { @class = "abc" }) %>

which generates:

<a href="/controller/action" class="abc">text</a>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜