I don't know what you know about the differences between the two keywords const and readonly. I didn't know exactly what they are, so if you don't know exactly what they are, we can discuss it together. When learning about these two keywords, let's first take a look at static constants and dynamic constants.
Static constants:The compiler parses the constant during compilation and replaces the value of the constant with the value of the initialization.
WhileDynamic constantThe value is obtained at the moment of running. during compilation, the compiler marks it as a read-only constant instead of a constant value, so that Dynamic Constants do not have to be initialized during declaration, the initialization can be delayed in the constructor. Now let's explain const and readonly.
1. const-modified constants must be initialized during Declaration; readonly-modified constants can be delayed until constructor initialization.
2. const-modified constants are parsed during compilation, that is, the constant value is replaced with the initial value. readonly-modified constants are delayed until running.
3. const modifier constants focus on efficiency; readonly modifier constants focus on flexibility
4. const modified constants do not consume memory; readonly consumes memory because it needs to save constants.
5. const can only modify the primitive type, enumeration class, or string type. readonly does not have this restriction.
Example 1:
If a static field is added before const, it is obviously incorrect, because after const is compiled, it is already a static field.
After compilation, the const variable will be replaced with the variable value, which is why it is efficient.
pi = Main(
The printed variable code is already compiled
Console. WriteLine (double) 3.1415926 );
Example 2:
Next, let's take a look at the small example of readonly.
Person(.Name = Main(= Person(=
The Person Instance name is immutable after being assigned a value in the constructor. The following code will report an error after compilation.
Next, let's take a look at another situation.
Person(.Name = .Person = Main(= Worker( Person(= Person(=
View the compiled results
I don't know whether it can be said that readonly is flexible.
Example 3:
A = B * B = Main(
The result is simple.
The principle is also relatively simple, that is, static readonly is A dynamic constant, and the value of the variable is not parsed during compilation, so it is the default value at the beginning, for example, A and B are both int type, so they are all 0. When the program runs to A = B * 10; so A = 0*10 = 0, and the program then runs to B = 10, the true initial value 10 of B is assigned to B.
For the two keywords const and readonly, I have learned a lot. If you still have questions after reading this article, you can use the ILDASM tool provided by Microsoft.
Open the cmd command and enter ILDASM.
Open the exe file to view the IL execution process.