C # constants are mainly divided into two types: compile time and run time
The keyword const is used to define the compilation workload, and the keyword readonly is used to define the runtime workload.
Differences:
The constant value is used to replace the constant variable during compilation.
Run-Time, return a reference to the run-time variable.
What are the differences between the two variable reference methods?Code:
Reference the example in Objective C #: Define a class library limitation, which defines a class limitations. The Code is as follows:
Public Class Limitations
{
Public Static Readonly Int Startvalue = 5 ;
Public Const Int Endvalue = 10 ;
}
This class contains two quantities: one is the compile-time volume and the other is the run-time volume.
On the master nodeProgramTo reference the class library and call the related values of the class. The Code is as follows:
Static Void Main ( String [] ARGs)
{
For ( Int I = Limitations. startvalue; I < Limitations. endvalue; I ++ )
{
Console. writeline (I. tostring ());
}
Console. Read ();
}
Running result:
5
6
7
8
9
Now let's update the Assembly limitation. The Code is as follows:
Public Class Limitations
{
Public Static Readonly Int Startvalue = 105 ;
Public Const Int Endvalue = 120 ;
}
Generate and replace the original assembly. The running result is nothing.
Why? It turns out to be related to the execution behavior of the two variables. during compilation, all the compilation constant variables will be replaced with their values. When you change the assembly, in the referenced program, the value of the original compilation constant does not change, so endvalue is still 10. For runtime variables, because runtime variables are retained for reference, therefore, the original value will be replaced with a new value, resulting in the startvalue of 105. so there is no running result.
From the example above, we can see the use of the two variables. If you want to make the program have good maintainability, you can choose the runtime variable.
For the compilation constant, because the variable has been replaced by the value during compilation, the program performance can be slightly improved, so if the program is rarely changed, you can select the compile time.