隐式枚举转换允许把十进制整数转换成任何枚举类型,对应其它的整数则不存在这种隐式转换。请看下面的例子:
using System;
enum WeekDay
{
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
class Test
{
static void Main(string[] args)
{
WeekDay day;
day = 0;
Console.WriteLine(day);
Console.ReadLine();
}
}
enum WeekDay
{
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
class Test
{
static void Main(string[] args)
{
WeekDay day;
day = 0;
Console.WriteLine(day);
Console.ReadLine();
}
}
程序的输出是:
Sunday
但如果我们把day = 0改写为day = 1,编译器就会给出错误:
我们应该使用显示枚举转换
day = (WeekDay)3;//Wednesday
Console.WriteLine(day);
Console.WriteLine(day);