枚举类型的一点研究
由于我本人是直接从Java开始学习.Net的(,没办法,项目需要,自学成才),到现在还是有些基础知识不是很牢靠,所以就萌发了写一系列的有关.Net基础文章。今天研究的对象是枚举类型。先看如下的代码:
ok,csc编译运行一下,看看结果:
Today is Wendsday
First day on weekend is Saturday
Days in Month is 31
看起来没什么问题啊,好,现在把上面的代码改动一处,把最后一句 Console.WriteLine("Days in Month is " + (int)days);改成 Console.WriteLine("Days in Month is " + days);重新编译运行一下,再看看结果:
Today is Wendsday
First day on weekend is Saturday
Days in Month is Jul
奇怪了,明明days是“Jan”,为什么显示出来的是“Jul”呢?请再把代码中的“DaysOfMonth”枚举变量改成如下的定义:enum DaysOfMonth {Jan = 131, Feb = 228, Mar = 331, Apr = 430, May = 531, Jun = 630, Jul = 731, Aug = 831, Sep = 930, Oct = 1031, Nov = 1130, Dec = 1231 },重新编译再运行一下,看看结果:
Today is Wendsday
First day on weekend is Saturday
Days in Month is Jan
这次没问题了,“days”可以正确显示了。这说明了,如果对enum变量进行定义的时候,给每个枚举常量赋了整型值,如果整型值有重复的,而你又最终不是通过转型取整型值而是直接去取枚举变量本身,则可能取不到你想要的值。我猜测取值的算法是随机的,开始我作简单测试的时候,以为还是有规律的,一度以为是以当前要取值的枚举常量后第一个匹配的常量,后来发现是错误的。不知道我猜的对不对,欢迎大家指教!
using System;
enum Weekdays { Monday=1, Tuesday, Wendsday, Thursday, Friday }
enum Weekends { Saturday=6, Sunday }
enum DaysOfMonth {Jan = 31, Feb = 28, Mar = 31, Apr = 30, May = 31, Jun = 30, Jul = 31, Aug = 31, Sep = 30, Oct = 31, Nov = 30, Dec = 31 }
class TestApp
{
public static void Main(string[] args)
{
Weekdays Today = Weekdays.Wendsday;
Console.WriteLine("Today is " + Today);
Weekends weekend;
weekend = Weekends.Saturday;
Console.WriteLine("First day on weekend is " + weekend);
DaysOfMonth days = DaysOfMonth.Jan;
Console.WriteLine("Days in Month is " + (int)days);
}
}
enum Weekdays { Monday=1, Tuesday, Wendsday, Thursday, Friday }
enum Weekends { Saturday=6, Sunday }
enum DaysOfMonth {Jan = 31, Feb = 28, Mar = 31, Apr = 30, May = 31, Jun = 30, Jul = 31, Aug = 31, Sep = 30, Oct = 31, Nov = 30, Dec = 31 }
class TestApp
{
public static void Main(string[] args)
{
Weekdays Today = Weekdays.Wendsday;
Console.WriteLine("Today is " + Today);
Weekends weekend;
weekend = Weekends.Saturday;
Console.WriteLine("First day on weekend is " + weekend);
DaysOfMonth days = DaysOfMonth.Jan;
Console.WriteLine("Days in Month is " + (int)days);
}
}
ok,csc编译运行一下,看看结果:
Today is Wendsday
First day on weekend is Saturday
Days in Month is 31
看起来没什么问题啊,好,现在把上面的代码改动一处,把最后一句 Console.WriteLine("Days in Month is " + (int)days);改成 Console.WriteLine("Days in Month is " + days);重新编译运行一下,再看看结果:
Today is Wendsday
First day on weekend is Saturday
Days in Month is Jul
奇怪了,明明days是“Jan”,为什么显示出来的是“Jul”呢?请再把代码中的“DaysOfMonth”枚举变量改成如下的定义:enum DaysOfMonth {Jan = 131, Feb = 228, Mar = 331, Apr = 430, May = 531, Jun = 630, Jul = 731, Aug = 831, Sep = 930, Oct = 1031, Nov = 1130, Dec = 1231 },重新编译再运行一下,看看结果:
Today is Wendsday
First day on weekend is Saturday
Days in Month is Jan
这次没问题了,“days”可以正确显示了。这说明了,如果对enum变量进行定义的时候,给每个枚举常量赋了整型值,如果整型值有重复的,而你又最终不是通过转型取整型值而是直接去取枚举变量本身,则可能取不到你想要的值。我猜测取值的算法是随机的,开始我作简单测试的时候,以为还是有规律的,一度以为是以当前要取值的枚举常量后第一个匹配的常量,后来发现是错误的。不知道我猜的对不对,欢迎大家指教!