码迷,mamicode.com
首页 > 其他好文 > 详细

如何获取枚举字符串,值及遍历枚举(转)

时间:2017-04-28 10:27:15      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:ring   blog   tostring   stat   输出   方法   example   break   main   

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

如何获取枚举字符串,值及遍历枚举(转)

标签:ring   blog   tostring   stat   输出   方法   example   break   main   

原文地址:http://www.cnblogs.com/jack-yan/p/6780221.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!