如何获取枚举字符串,值及遍历枚举(转)
Posted jack-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何获取枚举字符串,值及遍历枚举(转)相关的知识,希望对你有一定的参考价值。
http://www.cnblogs.com/fanwenxuan/archive/2007/10/16/926019.html
枚举是一个特定的常量集合组成的独特类型
using System;
public enum TimeOfDay
{
Morning = 0,
Afternoon = 1,
Evening
}
class EnumExample
{
public static int Main()
{
//调用方法
WriteGreeting(TimeOfDay.Morning);
//获取枚举字符串
TimeOfDay time = TimeOfDay.Afternoon;
Console.WriteLine(time.ToString());
//获取枚举字符串的值
TimeOfDay time2 = (TimeOfDay) Enum.Parse(typeof(TimeOfDay), "Evening", true);
Console.WriteLine((int)time2);
// 遍历所有的枚举元素
Type time3=typeof(TimeOfDay);
foreach(string s in Enum.GetNames(time3))
{
Console.WriteLine(s);
}
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;
}
}
}
输出结果:
Good Morning!
Afternoon
2
Morning
Afternonn
Evening
以上是关于如何获取枚举字符串,值及遍历枚举(转)的主要内容,如果未能解决你的问题,请参考以下文章