为什么我会在只读字段上选择私有只读 auto-属性?

Why would I choose a private read-only auto-property over a read-only field?

一个 article about changes in C# 6.0 at Microsoft 呈现只读的自动属性和声明(由我自己强调):

An interesting consequence of support for auto-property initializers is that it eliminates many of the cases found in earlier versions where you needed explicit field declarations. (...) On the other hand, the need to declare read-only fields becomes virtually deprecated. Now, whenever a read-only field is declared, you can declare a read-only auto-property possibly as private, if that level of encapsulation is required.

我到底为什么要这么做?

我完全理解 exposting 属性而不是字段的好处,因为即使在我需要在更高版本中添加一些验证代码或类似代码的情况下,这也能保持二进制兼容性。但是 always 拥有私有只读字段 属性 比私有只读字段有什么好处?

请注意,我不是在询问私有只读 属性 比私有只读字段有优势的特定场景。引用的文章暗示只要可以使用私有只读字段,就应该选择私有只读 属性。这是否有任何切实的好处,或者这只是作者对新功能的过度热情?

我替换了完整的上下文。这句话在章节Primary Contructors. With primary constructors, it make sense to replace read-only backing field by Auto-Property Initializers.

我同意,这句话很奇怪:

Now, whenever a read-only field is declared, you can declare a read-only auto-property possibly as private, if that level of encapsulation is required.

当我读到这篇文章时,我看到了两个公理:

  1. 对于主构造函数,您应该使用自动 属性 初始化程序而不是只读支持字段。
  2. 嘿伙计,可能用自动初始化程序private
  3. 声明属性

我认为作者更喜欢简洁而不是可读性,或者作者提倡到领域的尽头。

但是主构造函数并没有集成到最终的C#6或后续版本中,所以我们仍然需要很长时间的支持字段。