何时在 OOP 中对类字段使用 public 修饰符?

发布于 2025-01-10 12:29:21 字数 1436 浏览 4 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

寂寞陪衬 2025-01-17 12:29:21

根据 C# 编码约定 public field 应该谨慎使用

// A public field, these should be used sparingly
public bool IsValid;

为什么?我认为因为:

  • 则可以由类的任何其他用户编辑
  • 如果您想向字段添加一些逻辑, ,那么您需要创建属性而不是字段。通过这样做,您将打破类的合同,
  • 不可能覆盖变量

但是,在某些情况下您需要将字段设置为 @VGR 说:

public const string foo = "";

According to the C# coding conventions public field should be used sparingly:

// A public field, these should be used sparingly
public bool IsValid;

Why? I think because of:

  • can be edited by any other user of class
  • if you want to add some logic to field, then you need to create property instead of field. By doing this, you will break a contract of class
  • it is not possible to override variable

However, there is a case when you need to have field as @VGR said:

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