枚举是用户定义的整数类型。在声明一个枚举时,要指定该枚举可以包含的一组可接受的实例值。
using System;
namespace ConsoleApplication3
{
classProgram
{
staticvoid Main(string[] args)
{
WriteGreeting(TimeOfDay.afternoon);
// 从字符串中获取枚举值,并转换为整数
TimeOfDay time2 = (TimeOfDay)Enum.Parse(typeof(TimeOfDay), "afternoon", true);
Console.WriteLine((int)time2);
Console.ReadLine();
}
staticvoid WriteGreeting(TimeOfDay timeOfDay)
{
switch (timeOfDay)
{
caseTimeOfDay.morning:
Console.WriteLine("Good morning!");
break;
caseTimeOfDay.afternoon:
Console.WriteLine("Good afternoon!");
break;
caseTimeOfDay.evening:
Console.WriteLine("Good evening!");
break;
default:
Console.WriteLine("Hello!");
break;
}
}
publicenumTimeOfDay
{
morning=0,
afternoon=1,
evening=2
}
}
}