Csharp/CSharp Tutorial/Class/const
Содержание
Define constants with const keywords
- The const modifier is used to declare fields or local variables that cannot be changed.
- These variables must be given initial values when they are declared.
- const implies static.
<source lang="csharp">using System;
class Constants
{
public const int value1 = 33; public const string value2 = "Hello";
} class MainClass {
public static void Main() { Console.WriteLine("{0} {1}", Constants.value1, Constants.value2); }
}</source>
33 Hello
Local Constants
<source lang="csharp">using System; class MainClass {
static void Main() { const double PI = 3.1416; double area = 2 * 2 * PI; Console.WriteLine("Radius: {0}, Area: {1}", 2, area); }
}</source>
Radius: 2, Area: 12.5664
The use of "const int"
<source lang="csharp">class MainClass {
public static void Main() { const int Length = 3; System.Console.WriteLine(Length); }
}</source>
3
Use expressions to calculate and display the circumference of a circle
<source lang="csharp">class MainClass {
public static void Main() { const double Pi = 3.14159; double diameter = 2.5; double circumference = Pi * diameter; System.Console.WriteLine("Circumference = " + circumference); }
}</source>
Circumference = 7.853975