C# 支持两种特殊的值类型:枚举和结构。
声明枚举:声明时要声明所有可能的值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
enumType
{
enum
Season
// enum 类型定义在 class 外面
{
Spring, Summer, Fall, Winter
// 最后一个元素后面不加" ; "
}
class
Program
{
//enum Season // 枚举变量定义在此处也可以
//{
// Spring, Summer, Fall, Winter
//}
static
void
Main(
string
[] args)
{
Season beauty = Season.Fall;
Season coldSeason = Season.Winter;
Season currentSeason = Season.Summer;
Console.WriteLine(
"The beautiful season is {0}."
, beauty);
// 用 WriteLine 显示枚举变量时,编译器会自动生成代码,输出和变量值匹配的字符串
Console.WriteLine(
"The beautiful season is {0}."
, beauty.ToString());
// 也可以使用 ToString 方法,显式地将一个枚举变量转换成代表其当前值的一个字符串
Console.WriteLine(
"The current season is {0}."
, currentSeason);
Console.WriteLine(
"{0} is very cold."
, coldSeason);
}
}
}
|
运行后结果如下:
在枚举的内部,它的每个元素都关联(对应)着一个整数值。默认情况下,第一个对应整数 0,以后每个元素所对应的整数都递增 1。我们可以获取一个枚举变量的基础整数值,为此,必须先将它转换为基本类型。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
enumType
{
enum
Season
// enum 类型定义在 class 外面
{
Spring, Summer, Fall, Winter
// 最后一个元素后面不加" ; "
}
class
Program
{
static
void
Main(
string
[] args)
{
Season currentSeason = Season.Summer;
Console.WriteLine(
"Summer is {0}"
, (
int
)currentSeason);
// 枚举的基础整数值
}
}
}
|
运行后结果如下:
也可以把一个特定的整数常量和一个枚举类型的文字常量关联起来。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
enumType
{
enum
Season
// 定义为 short 可以节省空间
{
Spring = 168, Summer, Fall, Winter
// 最后一个元素后面不加" ; "
}
class
Program
{
static
void
Main(
string
[] args)
{
Console.WriteLine(
"Spring is {0}"
, (
int
)Season.Spring);
// 168
Console.WriteLine(
"Summer is {0}"
, (
int
)Season.Summer);
// 169 依次 +1
Console.WriteLine(
"Fall is {0}"
, (
int
)Season.Fall);
// 170
Console.WriteLine(
"Winter is {0}"
, (
int
)Season.Winter);
// 171
}
}
}
|
运行后结果如下:
多个枚举文字常量可能拥有相同的基础值,可以像如下这样声明。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
enumType
{
enum
Season
// enum 类型定义在 class 外面
{
Spring, Summer, Fall, Autumn = Fall, Winter
// 最后一个元素后面不加" ; "
}
class
Program
{
static
void
Main(
string
[] args)
{
Console.WriteLine(
"Spring is {0}"
, (
int
)Season.Spring);
// 0
Console.WriteLine(
"Summer is {0}"
, (
int
)Season.Summer);
// 1
Console.WriteLine(
"Fall is {0}"
, (
int
)Season.Fall);
// 2
Console.WriteLine(
"Autumn is {0}"
, (
int
)Season.Autumn);
// 2 基础值相同
Console.WriteLine(
"Winter is {0}"
, (
int
)Season.Winter);
// 3
}
}
}
|
运行后结果如下:
声明枚举时,枚举的文字常量将默认获得 int 类型的值。但可以选择枚举的基本类型。