When creating a value type instance, we should try to implement it as constant and Atomic. The so-called constant, that is, the object will not be changed after it is created, similarProgramA constant defined in. Once a value type is created, it can be regarded as a constant state. In this way, it is thread-safe.
Atomicity refers to some correlated fields in the value type, such as birthdate and age. Age is calculated based on birthdate. if the object is used only to modify the age, without changing the birthday, the result is obviously incorrect. All atomic types are single entities. We need to maintain the associated fields at the same time.
The following two steps can be taken to construct a constant value type: 1) Declare the private field in the type as readonly; 2) set the attribute in the type to read-only, deletes the Set Method of the attribute.
It should be noted that in the process of converting the value type to the constant type, the so-called constant is the data stored by the pointer in the "stack, for data stored in the "Heap", it is not enough to simply use readonly settings. Here the "constant" only indicates that the memory address pointing to the "Heap" will not change, we can change the value in the corresponding memory in other ways. To solve this problem, we need to make defensive copies of the data in the "heap.
There are usually three ways to initialize the constant type:
- Provides a suitable constructor set.
- Create by using the factory method.
- Provides a helper class.