Why does Microsoft advise against readonly fields with mutable values?

前端 未结 7 869
予麋鹿
予麋鹿 2020-12-28 12:34

In the Design Guidelines for Developing Class Libraries, Microsoft say:

Do not assign instances of mutable types to read-only fields.

相关标签:
7条回答
  • 2020-12-28 13:29

    DO NOT assign instances of mutable types to readonly fields.

    I had a quick look in the Framework Design Guidelines book (pages 161-162), and it basically states what you've already noticed yourself. There's an additional comment by Joe Duffy that explains the guideline's raison-d'être:

    What this guideline is trying to protect you from is believing you've exposed a deeply immutable object graph when in fact it is shallow, and then writing code that assumes the whole graph is immutable.
    — Joe Duffy

    I personally think that the keyword readonly was named badly. The fact that it only specifies the const-ness of the reference, and not of the const-ness of the referenced object, easily creates misleading situations.

    I think it would have been preferable if readonly made referenced objects immutable, too, and not just the reference, because that is what the keyword implies.

    To remedy this unfortunate situation, the guideline was made up. While I think that its advice is sound from the human point of view (it's not always obvious which types are mutable and which aren't without looking up their definition, and the word suggests deep immutability), I sometimes wish that, when it comes to declaring const-ness, C# would offer a freedom similar to that offered by C++, where you can define const either on the pointer, or on the pointed-to-object, or on both or nothing.

    0 讨论(0)
提交回复
热议问题