In C #, when using the constant symbol const, the compiler first finds the symbol in the metadata of the module that defines the constant, takes the value of the constant directly, and then embeds it into the generated IL code, so the constant does not need to allocate any memory at run time, and of course it cannot get the address of the constant. You cannot use a reference.
The following code:
Copy Code code as follows:
public class Consttest
{
public const int constint = 1000;
}
Compile it into a ConstTest.dll file and refer to this ConstTest.dll file in the following code.
Copy Code code as follows:
Using System;
Class Program
{
public static void Main (string[] args)
{
Console.WriteLine (consttest.constint);//result output is 1000;
}
}
Compile to run this Main.exe program, the result output is 1000. Then delete the ConstTest.dll reference file in the Bin folder, run the Main.exe file directly, the program runs normally, the result output 1000.
If you redefine consttest as:
Copy Code code as follows:
public class Consttest
{
Can only be declared at the time of definition
public const int constint = 1000;
public readonly int readonlyint = 100;
public static int staticint = 150;
Public Consttest ()
{
Readonlyint = 101;
Staticint = 151;
}
Static front modifier not additive
Static Consttest ()
{
Static variables can only be initialized here
Staticint = 152;
}
}
Recompile to ConstTest.dll and add this reference to the caller program Main, then compile the calling program to generate a new Main.exe, even after the ConstTest.dll file is deleted again, the Main.exe runs normally, resulting in output 1000.
Change the main program as follows:
Copy Code code as follows:
Class Program
{
public static void Main (string[] args)
{
Console.WriteLine (consttest.constint);//Output 1000
Console.WriteLine (consttest.staticint);//Output 152
consttest mc = new Consttest ();
Console.WriteLine (consttest.staticint);//Output 151
}
}
Recompile the main program, and if you delete the ConstTest.dll at this point, you will get an error.
As you can see, if some engineering references to ConstTest.dll, if later because of the change, changed the value of the Constint constant, even if the reference to recompile ConstTest.dll, can not change the data in Main.exe ( You can change the Constint value to another value and then try to copy the compiled ConstTest.dll to the Main.exe Bin folder, where you can add only ConstTest.dll references and recompile the main program.