在 C# 中区分类名和属性的良好命名约定是什么?

发布于 2024-09-02 12:30:44 字数 295 浏览 3 评论 0原文

我经常遇到这种情况,所以我想我应该看看其他人对此有何评论。

使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冷了相思 2024-09-09 12:30:44

这实际上是.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.

窗影残 2024-09-09 12:30:44

当任何给定类中只有一个 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 the ProjectManager type.

Of course, if there are other uses, then you need different names.

鸠书 2024-09-09 12:30:44

我同意其他答案。为了完整起见,有时我会找到一种方法来概括类名。我知道您的示例只是一个示例,但一种方法是:

public class Person
{
  // Stuff here
}

public class OtherClass
{
  private Person ProjectManager { get; set; }
}

这有助于使其更具可读性。但具有相同的类名和属性是完全可以接受的(甚至是鼓励的)。

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:

public class Person
{
  // Stuff here
}

public class OtherClass
{
  private Person ProjectManager { get; set; }
}

This helps make it a bit more readable. But it is perfectly acceptable (and even encouraged) to have identical class name and property.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文