C# 类中的 @namespace 字段是什么?
我正在浏览StyleCop的源代码,我发现了一个奇怪的东西:
/// <summary>
/// The namespace that the rule is contained within.
/// </summary>
private string @namespace;
// [...]
internal Rule(string name, string @namespace, string checkId, string context, bool warning) : this(name, @namespace, checkId, context, warning, string.Empty, null, true, false)
{
Param.Ignore(name, @namespace, checkId, context, warning);
}
这是什么东西?它只是一个简单的字段,其中使用 at 符号来指示它是一个字段,而不是 namespace
关键字吗?如果是这样,at 符号可以用于任何保留字(例如 @dynamic
、@using
等)吗?
I'm browsing the source code of StyleCop, and I found a curious thing:
/// <summary>
/// The namespace that the rule is contained within.
/// </summary>
private string @namespace;
// [...]
internal Rule(string name, string @namespace, string checkId, string context, bool warning) : this(name, @namespace, checkId, context, warning, string.Empty, null, true, false)
{
Param.Ignore(name, @namespace, checkId, context, warning);
}
What is this thing? Is it just a simple field where at-sign is used to indicate that it is a field, and not a namespace
keyword? If so, may at-sign be used for any reserved word (for example @dynamic
, @using
, etc.)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
基本上是的。在变量名前面放置@可以阻止由于该变量名是关键字而发生的错误。
http://msdn.microsoft.com/en-us/库/x53a06bb(VS.71).aspx
Bascially yes. Putting a @ in front of the variable name stops an error ocurring due to that variable name being a keyword.
http://msdn.microsoft.com/en-us/library/x53a06bb(VS.71).aspx
是的,@ 符号可以放在保留字前面,以允许它们用作变量名。
实际上,我从这个问题中了解到了这一点以及其他事情
Yes @ sign may be put in front of reserved words to allow them to be used as variable names.
I actually learned that, and other things, from this question
是的,您可以使用
@
作为变量的第一个且唯一的第一个
字符。Yes, you can use
@
as thefirst and only first
character of your variable.该技术通常与自动代码生成配合使用,因为可以生成作为目标语言中的关键字的标识符,例如,如果 Xml 模式在其上运行代码生成以生成 C# 类,则该模式可能具有称为“事件”的属性。这是一个 C# 关键字,因此代码生成器可以改用“@event”。
This technique is usually paired with automatic code generation, as identifiers may be produced that are keywords in a target language, e.g. if an Xml schema has code generation run over it to produce C# classes, the schema may have an attribute called "event". This is a C# keyword, so the code generator can instead use "@event".
正如其他人回答的那样,确切地说,您可以使用保留关键字,只要在前面加上“@”前缀即可,但是恕我直言,这不是一个好的开发实践。我宁愿只在机器生成的代码中使用它(例如,在我工作的公司中,我们有一个将 Java 代码转换为 C# 的工具;因为在 Java 中“事件”不是保留字,所以我们的 Java 源代码可能会包含此类标识符)
最佳
阿德里亚诺
As the other people answered, exactly, you can use reserved keywords as long as you prefix then with '@', but IMHO, that's not a good development practice. I'd rather use it only in machine generated code (for instance, in the company I work for, we have a tool that converts Java code to C#; since in Java "event" is not a reserved word, our Java source code may contain such identifiers)
Best
Adriano