2018年7月6日 星期五

[C#] Enum列舉的使用方法

Enum.ToObject(Type, Object):將具有整數值的指定物件轉換為列舉成員。

Enum.GetName(Type, Object):擷取有指定數值之指定列舉的常數名稱。

Enum.GetNames(Type):在指定的列舉中擷取常數名稱的陣列。

Enum.GetValues(Type):在指定的列舉中擷取常數值的陣列。

Enum.IsDefined(Type, Object):傳回具有指定數值的常數是否存在於指定列舉的指示。

Enum.Parse(Type, String):把一或多個列舉常數的名稱或數值的字串表示轉換為一個相等列舉物件。

Enum.TryParse(String, TEnum):把一或多個列舉常數的名稱或數值的字串表示轉換為一個相等列舉物件。 指出轉換是否成功的傳回值。

列舉的基本應用:

public enum Week
{
   Monday = 1,
   Tuesday = 2,
   Wednesday = 3,
   Thursday = 4,
   Friday = 5,
   Saturday = 6,
   SunDay = 7,
}

public static string Schedule(Week day)
{
   string schedule = string.Empty;
   switch (day)
   {
      case Week.Monday:
         schedule = "The schedule of Monday.";
         break;
      case Week.Tuesday:
         schedule = "The schedule of Tuesday.";
         break;
      case Week.Wednesday:
         schedule = "The schedule of Wednesday.";
         break;
      case Week.Thursday:
         schedule = "The schedule of Thursday.";
         break;
      case Week.Friday:
         schedule = "The schedule of Friday.";
         break;
      case Week.Saturday:
         schedule = "The schedule of Saturday.";
         break;
      case Week.SunDay:
         schedule = "The schedule of SunDay.";
         break;
      };
      return schedule;
}

public static void Main(string[] args)
{
   Console.WriteLine(Schedule(Week.Friday));
   Console.WriteLine(Schedule((Week)7));
}

列舉的反映應用:

public enum Week
{
   Monday = 1,
   Tuesday = 2,
   Wednesday = 3,
   Thursday = 4,
   Friday = 5,
   Saturday = 6,
   SunDay = 7,
}

public static void Main(string[] args)
{
   Console.WriteLine(Enum.IsDefined(typeof(Week), "Saturday"));
   Console.WriteLine(Enum.IsDefined(typeof(Week), 5));

   var myDay = Enum.ToObject(typeof(Week), 3);
   Console.WriteLine(myDay);

   var values = Enum.GetValues(typeof(Week));
   foreach (var item in values)
   {
      Console.WriteLine(item);
   }

   var names = Enum.GetNames(typeof(Week));
   foreach (var item in names)
   {
      Console.WriteLine(item);
   }

   string name = Enum.GetName(typeof(Week), 7);
   Console.WriteLine(name);

   Console.WriteLine((int)Week.Monday);
}

沒有留言:

張貼留言