若要定義整數類型(int、byte 等)的常量值,使用枚舉類型。
若要定義非整型常量,一種方法是將它們分組到單個名爲 Constants 的靜態類中。 這要求對常量的所有引用都使用該類名作爲前綴。
示例:
static class Constants
{
public const double Pi = 3.14159;
public const int SpeedOfLight = 300000; // km per sec.
}
class Program
{
static void Main()
{
double radius = 5.3;
double area = Constants.Pi * (radius * radius);
int secsFromSun = 149476000 / Constants.SpeedOfLight; // in km
}
}