枚舉是用戶定義的整數類型。
namespace ConsoleApplication1 {/// <summary>/// 在枚舉中使用一個整數值,來表示一天的階段/// 如:TimeOfDay.Morning返回數字0/// </summary>class EnumExample{public enum TimeOfDay{Morning = 0,Afternoon = 1,Evening = 2}public static void Main(){WriteGreeting(TimeOfDay.Morning);//獲取枚舉的字符串表示TimeOfDay time = TimeOfDay.Afternoon;Console.WriteLine(time.ToString()); //返回字符串Afternoon//從字符串中獲取枚舉值,并轉換為整數TimeOfDay time2 = (TimeOfDay)Enum.Parse(typeof(TimeOfDay), "afternoon", true);Console.WriteLine((int)time2); //返回數字1 Console.ReadKey();}/// <summary>/// 把枚舉合適的值傳給方法,并在switch中迭代可能的值/// </summary>/// <param name="timeOfDay"></param>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;}}} }
?