In. in net, the const keyword is usually used to declare constants, but sometimes some constants are read from a configuration file or database. once read, they are no longer changed, what should we do at this time? In fact, it is very simple to use static constructors of classes.
When using this static constructor, add the readonly keyword to the variable so that the variable can be a read-only attribute after initialization, and others can no longer change it. The Code is as follows.
Public class Class1
...{
Public static readonly string s = "1 ";
Static Class1 ()
...{
S = "3 ";
}
}
The code for reading constant S is as follows:
Class Program
...{
Static void Main (string [] args)
...{
Console. writeline (class1.s );
}
}
At this time, we will find that the value 3 is printed on the screen, that is, the constant is already set in the static constructor, And it is read-only and cannot be changed. Note that the static constructor does not have the modifier such as public. If the modifier is added, the compilation fails.