const constant Field Use method
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Namespace project5_42
{
Class Program
{
static void Main (string[] args)
{
Convertunits cu = new Convertunits ();
Const-decorated fields are automatically compiled to static type fields at compile time and can be accessed directly from the class name.
However, if the declaration shows that the declaration is static, it causes the compilation to fail
Console.WriteLine (Convertunits.cupspergallon);
}
}
Class Convertunits
{
Public Const FLOAT Centimetersperinch = 2.54F;
public const int Cupspergallon = 16;
Const Type field declaration cannot be declared as static
public static const float pi=3.141592654f;
}
}
thepublic constant should be constant, because one assembly references constants in another assembly, constants are compiled directly into the referenced assembly, and when the constants in the referenced assembly change, if there is no
To recompile, the constants in the referenced assembly will still be the original values. ”
The preceding paragraph was validated in VS2013, including creating a DLL project in the same solution and a project referencing this DLL, and creating a DLL project in one project and referencing it in another project, in the case of compiling only the DLL project without compiling the project referencing the DLL. The changes made to constants in the DLL project are still correctly reflected in the referenced project, and there is no problem that the author mentions. But in order to avoid being foolproof, it is best to avoid such use, but instead use the readonly field as described below by the author.
Values that may change in the future should be specified as readonly and not as constants.
The ReadOnly modifier can only be used for fields that indicate that the value of a field can only be changed from the constructor, or directly at the time of declaration. The difference from const usage is that const is suitable for constant amounts such as pi, the gamma-ReadOnly, and that the ReadOnly field of each instance can be different, except that the ReadOnly field can be assigned at execution time, and that it is initialized in the constructor. Const can only be assigned at compile time. The ReadOnly field needs to be initialized in the constructor, so the compiler requires the ReadOnly field to be accessible outside the property, but in addition to this exception, do not access the support fields of the property from anywhere other than the containment property.
C # constant Fields