Chapter 8Constants and fields
I. Constants
1. The following types can be defined as constants:
2 primitive types: Boolean, Char, byte, sbyte, decimal, int16, int32, uint16, uint32, int64, uint64, single, double
2 string: String
2 Enumeration type
2. constants are directly embedded into the Il code after compilation. Therefore, constants in one module cannot be obtained by another module at runtime, the changes made to Constants by the former cannot be perceived by the other module at runtime. Therefore, read-only fields should be used to obtain "constant values" during runtime.
2. Fields
1. All fields (including static, instance, or read-only fields) are allocated memory at runtime.
2. the read-only field can only be assigned a value in the constructor. (It can also be directly assigned a value when declared. It is not allowed in other places. It is actually equivalent to assigning a value in the constructor ), the static read-only field is assigned a value in the Type constructor, And the instance read-only field is given a value in the instance constructor.
3. Static read-only fields can only be accessed by type names, but cannot be accessed by instance reference.
Iii. Differences between static read-only fields and constants:
1. constants are directly embedded into the Il code at the time of compilation, and cannot be re-read at runtime. Static read-only fields can be re-read at runtime.
2. constants can only be assigned values in the declaration, while static read-only fields can be assigned values in the constructor.