Why does Microsoft advise against readonly fields with mutable values?

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

    The syntax you are looking for is supported by the C++/CLI language:

    const Example^ const obj;
    

    The first const makes the referenced object immutable, the 2nd makes the reference immutable. The latter is equivalent to the readonly keyword in C#. Attempts to evade it produce a compile error:

    Test^ t = gcnew Test();
    t->obj = gcnew Example();   // Error C3892
    t->obj->field = 42;         // Error C3892
    Example^ another = t->obj;  // Error C2440
    another->field = 42; 
    

    It is however smoke and mirrors. The immutability is verified by the compiler, not by the CLR. Another managed language could modify both. Which is the root of the problem, the CLR just doesn't have support for it.

提交回复
热议问题