问题描述
我曾多次看到 ReSharper 生成的代码如下所示:
Several times I've seen ReSharper generate code that looks like this:
delegate void myHandler(int i);
myHandler myHandlerContainer;
...
foreach (Delegate @delegate in myHandlerContainer.GetInvocationList())
{...}
@delegate 中的@"是否赋予该变量任何特殊的语义含义?
还是只是我以前没有遇到过的约定?
Does the '@' in @delegate give that variable any special semantic meaning?
Or is it just a convention I didn't encounter before?
推荐答案
更多细节来自 MSDN:
Some more details from MSDN:
前缀@
"允许使用关键字作为标识符,这在与其他编程语言交互时很有用.字符 @
实际上并不是标识符的一部分,因此标识符在其他语言中可能被视为普通标识符,没有前缀.带有 @
前缀的标识符称为逐字标识符.允许对不是关键字的标识符使用 @
前缀,但出于风格问题强烈建议不要使用.
The prefix "
@
" enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character@
is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an@
prefix is called a verbatim identifier. Use of the@
prefix for identifiers that are not keywords is permitted, but strongly discouraged as a matter of style.
来自 C# 语言规范:2.4.2 标识符.
前缀 '@
' 因此允许例如从名为delegate
"的类派生;这可能是在用 C# 以外的其他语言编写的库中定义的.
Prefixing with '@
' therefore allows e.g. to derive from a class named "delegate
" which might be defined in a library written in another language than C#.
在任何其他情况下,我都不建议使用这种语法,而是使用不同于 C# 关键字的标识符(例如,value
而不是 value
)以提高代码的可读性并避免混淆它是否有任何特殊含义.如果已完成,请正确评论为什么要这样做,以便其他人知道.
In any other case I would not recommend to use this syntax and rather make up identifiers different from the C# keywords (e.g. valu
instead of value
) to increase code readability and avoid confusion whether there is any special meaning attached to it. If it is done, properly comment as to why it was done so that others are aware.
还有一个关于变量命名的有趣事实:
There is also another interesting fact about variable naming mentioned there:
包含两个连续下划线字符 (U+005F
) 的标识符保留供实现使用.例如,实现可能会提供以两个下划线开头的扩展关键字.
Identifiers containing two consecutive underscore characters (
U+005F
) are reserved for use by the implementation. For example, an implementation might provide extended keywords that begin with two underscores.
这篇关于代表的@前缀有什么特殊含义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!