獲取當前列舉型別的基礎型別 C#


要返回當前列舉型別的基礎型別,程式碼如下所示 −

示例

 動態演示

using System;
public class Demo {
   enum Vehicle {Car, Bus, Bike, Airplane}
   public static void Main() {
      try {
         Vehicle v = Vehicle.Bike;
         Type type = v.GetType();
         string[] str = type.GetEnumNames();
         Console.WriteLine("GetEnumName() to return the constant name = " + str);
         Type type2 = type.GetEnumUnderlyingType();
         Console.Write("Enum Underlying type = "+type2);
         Console.WriteLine("
Listing constants ..");          for (int i = 0; i < str.Length; i++)             Console.Write("{0} ", str[i]);       }       catch (ArgumentException e) {          Console.WriteLine("Not an enum!");          Console.Write("{0}", e.GetType(), e.Message);       }    } }

輸出

這將產生以下輸出 −

GetEnumName() to return the constant name = System.String[]
Enum Underlying type = System.Int32
Listing constants ..
Car Bus Bike Airplane

示例

讓我們看另一個示例 −

 動態演示

using System;
public class Demo {
   enum Vehicle {Car, Bus, Bike, Airplane}
   public static void Main() {
      try {
         Type type = typeof(int);
         string[] str = type.GetEnumNames();
         Console.WriteLine("GetEnumName() to return the constant name = " + str);
         Type type2 = type.GetEnumUnderlyingType();
         Console.Write("Enum Underlying type = "+type2);
         Console.WriteLine("
Listing constants ..");          for (int i = 0; i < str.Length; i++)             Console.Write("{0} ", str[i]);       }       catch (ArgumentException e) {          Console.WriteLine("Not an enum!");          Console.Write("{0}", e.GetType(), e.Message);       }    } }

輸出

這將產生以下輸出 −

Not an enum!
System.ArgumentException

更新日期:06-12-2019

151 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告