如何根据类的名称空间正确命名类?
人们经常可以看到类名携带对其所属命名空间的引用。 最流行的示例之一是 .NET“Xml”命名空间,其中定义的每个类都以“Xml”标记为前缀。
这对我来说一直显得相当多余,但最近我意识到在某些情况下它可能很有用......但仍然是多余的。
我想知道人们实际上是如何处理这个问题的。
谢谢。
One can often see class names carrying a reference to the namespace to which they belong. One of the most popular examples is the .NET 'Xml' namespace where every single class defined in it is prefixed with the 'Xml' tag.
This has always seemed pretty redundant to me, but recently I've realized that in some cases it could be useful... but still redundant.
I'd like to know how people actually deal with this issue.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我采取的是“在适当的时候”的方法。 这个想法是您希望使用最有意义的名称来命名您的类。 在某些情况下,这确实意味着类名与命名空间有些多余,但请记住,命名空间通常不会被视为代码中类名的一部分,而是作为 using 指令的一部分。
命名空间用于将相关的类等逻辑分组在一起,以帮助开发人员找到正确的类并帮助最大限度地减少名称冲突的机会。
I take the "when it is appropriate" approach. The idea is that you want to name your classes using the name that makes the most sense. In some cases it does mean that the class name is somewhat redundant with the namespace, but keep in mind that the namespaces aren't generally seen as part of the class name in the code other than as part of a using directive.
The namespaces are used to logically group related classes, etc. together to help the developer find the correct classes and help minimize the chance of name collisions.
我倾向于遵循 Microsoft 关于命名问题的指南。
回复:斯科特的评论。
我认为 MS 在这个问题上非常清楚,这类似于你对 OP 的回复。 例如:
在OP的问题中,引用了Xml命名空间。 如果您查看其中这些类的名称,您会发现它们是非常常见的名称,没有前缀“Xml” - 属性、字典、文档等。
无论如何,就像我说的,我尝试遵循他们的建议。
I tend to defer to Microsoft's guidance on issues of naming.
Re: Scott's comment.
I think MS is pretty clear on the issue and it is akin to your reply to the OP. For instance:
In the OP's question, the reference was made to the Xml namespace. If you look at the names of those classes in there, they are pretty common names w/out the "Xml" prepended onto them - Attribute, Dictionary, Document, etc.
Anyhow, like I said, I try to follow what they suggest.
我喜欢 System.Xml 类具有 Xml 前缀。 它帮助我将它们与一般的对应物区分开来。 什么是文档与 XmlDocument? 有了前缀就变得更清楚了。 无论如何,我认为。
在我自己的课堂上,我努力遵循这种精神。 如果我采用一个通用的单词并将其包装在我的类中,我可能会选择使用名称空间作为前缀。 例如:
MyProject.Client.Application
将与Application
发生冲突,后者是一个 .NET 类。MyProject.Client.ClientApplication
将避免冲突问题,同时仍然清楚该类的作用(至少就我的项目而言)。I like that the System.Xml classes have the Xml prefix. It helps me distinguish them from a generic counterpart. What's a Document versus XmlDocument? It becomes clearer with the prefix. In my opinion, anyway.
In my own classes, I try to follow this spirit. If I'm taking a somewhat generic word and wrapping it in my class, I may choose to use the namespace as a prefix. For example:
MyProject.Client.Application
will collide withApplication
, which is a .NET class.MyProject.Client.ClientApplication
will avoid collision problems while still remaining clear as to what the class does (at least, in terms of my project).