枚举

枚举是用户定义的整数类型,在声明一个枚举时,要指定该枚举可以包含的一组可接受的实例值。不仅如此,还可以给值指定易于记忆的名称。

public enum TimeOfDay
{
Morning = 0,
Afternoon = 1,
Evening = 2
}


 

class EnumExample
{
public static int Main()
{
WriteGreeting(TimeOfDay.Morning);
return 0;
}
   static void WriteGreeting(TimeOfDay timeOfDay)
{
switch(timeOfDay)
{
case TimeOfDay.Morning:
Console.WriteLine("Good morning!");
break;
case TimeOfDay.Afternoon:
Console.WriteLine("Good afternoon!");
break;
case TimeOfDay.Evening:
Console.WriteLine("Good evening!");
break;
default:
Console.WriteLine("Hello!");
break;
}
}
}

可以获取枚举的字符串表示,例如使用前面的TimeOfDay枚举:

TimeOfDay time = TimeOfDay.Afternoon;
Console.WriteLine(time.ToString());

会返回字符串Afternoon。

另外,还可以从字符串中获取枚举值:

TimeOfDay time2 = (TimeOfDay) Enum.Parse(typeof(TimeOfDay), "afternoon", true);
Console.WriteLine((int)time2);


 

你可能感兴趣的:(Class)