Why does Microsoft advise against readonly fields with mutable values?

前端 未结 7 920
予麋鹿
予麋鹿 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:03

    It seems natural that if a field is readonly, you would expect to not be able to change the value or anything having to do with it. If I knew that Bar was a readonly field of Foo, I could obviously not say

    Foo foo = new Foo();
    foo.Bar = new Baz();
    

    But I can get away with saying

    foo.Bar.Name = "Blah";
    

    If the object backing Bar is, in fact, mutable. Microsoft is simply recommending against that subtle, counterintuitive behavior by suggesting that readonly fields be backed by immutable objects.

提交回复
热议问题