internalenum Color ...{ White, // Assigned a value of 0 Red, // Assigned a value of 1 Green, // Assigned a value of 2 Blue, // Assigned a value of 3 Orange // Assigned a value of 4 }
在看一下编译后的样子:
internalstruct Color : System.Enum ...{ publicconst Color White = (Color) 0; publicconst Color Red = (Color) 1; publicconst Color Green = (Color) 2; publicconst Color Blue = (Color) 3; publicconst Color Orange = (Color) 4; //包含Color的变量值,不能写代码直接引用这个实例字段 public Int32 value__; }
在看一下几种不同的输出Color值的方法
Color c = Color.Blue; Console.WriteLine(c); //“Blue” 泛型格式 Console.WriteLine(c.ToString()); //“Blue” 泛型格式 Console.WriteLine(c.ToString("G")); //“Blue” 泛型格式 Console.WriteLine(c.ToString("D")); //“3”十进制格式 Console.WriteLine(c.ToString("X")); //“03”十六进制格式
c#中的System.Enum类为我们提供了好多操作枚举类型的方法,下面举一个例子:
Color[] colors = (Color[]) Enum.GetValues(typeof(Color)); Console.WriteLine("Number of symbols defined: "+ colors.Length); Console.WriteLine("Value Symbol ----- ------"); Chapter 12: Enumerated Types and Bit Flags 289 foreach (Color c in colors) ...{ Console.WriteLine("{0,5:D} {0:G}", c); }
Value Symbol -------------------- 0 White 1 Red 2 Green 3 Blue 4 Orange