在 C# 中区分类名和属性的良好命名约定是什么?
我经常遇到这种情况,所以我想我应该看看其他人对此有何评论。
使用 StyleCop 约定,我发现我经常有一个很难与它正在访问的类名不同的属性名称。例如:
public class ProjectManager
{
// Stuff here
}
public class OtherClass
{
private ProjectManager ProjectManager { get; set; }
}
它可以编译并运行,但即使使用“this”,这似乎也是一种容易混淆的方法。
I run into this frequently enough that I thought I'd see what others had to say about it.
Using the StyleCop conventions, I find that I often have a property name that is hard to make different than the class name it is accessing. For example:
public class ProjectManager
{
// Stuff here
}
public class OtherClass
{
private ProjectManager ProjectManager { get; set; }
}
It compiles and runs, but seems like it would be an easy way to confuse things, even with the use of "this".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这实际上是.Net 编程中非常常见的模式。特别是对于枚举类型和成员,因为它是 .Net 设计指南推荐的编程方式。
4.0 设计指南参考
虽然它可能有点令人困惑,但只要您看过几次,就不会觉得这样了。这些工具很好地支持这种模式,并且给定一个是类型,另一个是实例,很难意外地反转它们而不导致编译错误。
This is actually a very common pattern in .Net programming. Particularly so with enum types and members as it's the .Net Design Guidelines recommended way of programming.
4.0 design guidelines reference
While it may be a bit confusing, it's not once you've seen it a few times. The tools well support this pattern and given one is a type and the other an instance it's hard to accidentally invert them without causing a compilation error.
当任何给定类中只有一个
ProjectManager
类型的属性时,这是典型的命名约定。它不再令人困惑,因为ProjectManager
类型没有其他用途。当然,如果有其他用途,那么就需要不同的名称。
That is a typical naming convention when there will only be a single property of type
ProjectManager
within any given class. It ceases to be confusing because there are no other uses of theProjectManager
type.Of course, if there are other uses, then you need different names.
我同意其他答案。为了完整起见,有时我会找到一种方法来概括类名。我知道您的示例只是一个示例,但一种方法是:
这有助于使其更具可读性。但具有相同的类名和属性是完全可以接受的(甚至是鼓励的)。
I agree with the other answers. For completeness sake, sometimes I find a way to generalize the class name a bit more. I understand your example was just an example, but one way to do it would be:
This helps make it a bit more readable. But it is perfectly acceptable (and even encouraged) to have identical class name and property.