C# @ modifier for methods parameters

北战南征 提交于 2019-12-09 14:04:11

问题


I was using ReSharper plugin on VS2010 and i was generating an interface method. ReSharper put an @ on the parameter name. WHat is that used for?

int Count(Func<ContratoList, bool> @where);

Whats the difference for

int Count(Func<ContratoList, bool> where);

Thanks!


回答1:


The @ symbol allows you to use reserved words in a variable name.

int @class = 1;

void MyMethod(int @goto);

bool @public { get; set; }

As Marc correctly pointed out in his comment and his answer, ReSharper is actually wrong to do this because where is a Contextual Keyword and is not actually a reserved word, so your method will compile without the @.




回答2:


In many ways, resharper is wrong to do this. where is a contextual keyword, meaning: it only acts as a keyword in some very specific scenarios (i.e. LINQ). In the position indicated, it actually does nothing. It would not be confused as a keyword there, as when the C# language designers add keywords to C# they need to ensure pre-existing code continues to compile (as far as possible), and that would have been legal in earlier C#.

The usage of @ also confuses/complicates some tools (razor, in particular, since razor already uses @ to indicate the start of code - meaning that for a variable using @ (i.e. @string) sometimes you need @ and sometimes you need @@ - and I know of at least one false-positive IDE warning this can cause).

However! If the parameter was if or class etc, then @if / @class allows you to use that as a variable name rather than getting confused as a C# keyword. That also isn't a great idea, note. But by the same token, we wouldn't start doing that to all our code (string @name = ... etc) - so why do it here? It isn't needed, and as demonstrated by this question, it has added confusion.

Personally, though, I'd find a parameter name that isn't a keyword or contextual-keyword.




回答3:


It allows you to use reserved keywords as variable names.




回答4:


It will stop this parameter acting like a keyword (as whereis a keyword in linq amongst other things).




回答5:


This is done because 'where' is a protected keyword in C# (LINQ)




回答6:


it allows you to use reserved words as params.



来源:https://stackoverflow.com/questions/8051508/c-sharp-modifier-for-methods-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!