枚举是一个被命名的整型常数的集合, 枚举在日常生活中很常见。
例如表示星期的SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY, 就是一个枚举。
枚举的说明与结构和联合相似, 其形式为:
enum 枚举名{
标识符[=整型常数],
标识符[=整型常数],
...
标识符[=整型常数],
} 枚举变量;
如果枚举没有初始化, 即省掉"=整型常数"时, 则从第一个标识符开始, 顺
次赋给标识符0, 1, 2, ...。但当枚举中的某个成员赋值后, 其后的成员按依次
加1的规则确定其值。
例如下列枚举说明后, x1, x2, x3, x4的值分别为0, 1, 2, 3。
enum string{x1, x2, x3, x4}x;
当定义改变成:
enum string
{
x1,
x2=0,
x3=50,
x4,
}x;
则x1=0, x2=0, x3=50, x4=51
注意:
1. 枚举中每个成员(标识符)结束符是",", 不是";", 最后一个成员可省略
","。
2. 初始化时可以赋负数, 以后的标识符仍依次加1。
3. 枚举变量只能取枚举说明结构中的某个标识符常量。
例如:
enum string
{
x1=5,
x2,
x3,
x4,
};
enum strig x=x3;
此时, 枚举变量x实际上是7。
在c#中
____________________________________________________________________________
using System;
public class GetNameTest {
enum Colors { Red, Green, Blue, Yellow };
enum Styles { Plaid, Striped, Tartan, Corduroy };
public static void Main() {
Console.WriteLine("The 4th value of the Colors Enum is {0}", Enum.GetName(typeof(Colors), 3));
Console.WriteLine("The 4th value of the Styles Enum is {0}", Enum.GetName(typeof(Styles), 3));
}
}
____________________________________
执行结果:
D:/Do***ents and Settings/Administrator>csc GetNameTest.cs
Microsoft (R) Visual C# .NET 编译器版本 7.10.6310.4
用于 Microsoft (R) .NET Framework 版本 1.1.4322
版权所有 (C) Microsoft Corporation 2001-2002。保留所有权利。
D:/Do***ents and Settings/Administrator> GetNameTest
The 4th value of the Colors Enum is Yellow
The 4th value of the Styles Enum is Corduroy