C# · 12月 29, 2021

c# – 代表的@前缀是否具有特殊含义?

几次我看到ReSharper生成的代码如下所示: delegate void myHandler(int i);myHandler myHandlerContainer;…foreach (Delegate @delegate in myHandlerContainer.GetInvocationList()){…}

@delegate中的“@”是否赋予该变量任何特殊的语义?
还是只是一个我以前没有遇到的惯例?

解决方法 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# Language Specification: 2.4.2 Identifiers.

因此,使用’@’进行前缀可以例如.从一个名为“delegate”的类派生,这个类可能在用C#编写的另一种语言的库中定义.

在任何其他情况下,我不建议使用这种语法,而是构成与C#关键字(例如,值而不是值)不同的标识符,以增加代码可读性,避免混淆是否存在任何特殊含义.

还有一个有趣的事实,关于在这里提到的变量命名:

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.