Csharp/CSharp Tutorial/Class/const — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 15:31, 26 мая 2010
Содержание
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.
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);
}
}
33 Hello
Local Constants
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);
}
}
Radius: 2, Area: 12.5664
The use of "const int"
class MainClass
{
public static void Main()
{
const int Length = 3;
System.Console.WriteLine(Length);
}
}
3
Use expressions to calculate and display the circumference of a circle
class MainClass
{
public static void Main()
{
const double Pi = 3.14159;
double diameter = 2.5;
double circumference = Pi * diameter;
System.Console.WriteLine("Circumference = " + circumference);
}
}
Circumference = 7.853975