If DateTime is immutable, why does the following work?

前端 未结 6 1459
轻奢々
轻奢々 2021-01-03 20:34

I thought I understood what Immutable meant, however I don\'t understand why the following compiles and works:

DateTime dt = DateTime.Now;

Console.WriteLine         


        
6条回答
  •  礼貌的吻别
    2021-01-03 21:25

    If an instance of a non-trivial structure type is stored in a writable storage location (non-readonly field, local variable, array slot, etc.), all of its fields will be mutable. If an instance is stored in a non-writable storage location (a readonly field, a compiler-generated temporary value, etc.), then none of its fields will be mutable. The concept of an "immutable structure type" is a misnomer, since the statement:

    myStruct1 = myStruct2; // Assume variables are of the same structure type
    

    will, if myStruct1 is writable, replace all public and private fields of myStruct1 with the corresponding fields of myStruct2; if myStruct1 isn't writable, the statement will generate a compile-time error. The code for the structure gets no say in the matter, and won't even be notified that the assignment as taken place.

    Although DateTime provides no means by which an existing DateTime instance can be modified except by whole-structure assignment, it can do nothing to prevent code from overwriting the fields of one instance with the contents of another, as happens with dateTimeVariable = DateTime.Now;.

提交回复
热议问题