2011-03-14 76 views
13

你怎麼能得到一個枚舉的底層/派生類型(字節,短,int等)?獲取底層/派生類型的枚舉?

+1

@ChrisF:尋找類型不是值。 – Will

+0

我的歉意。我誤解了另一個標題。如果我能收回我的近距離投票。刪除了自動插入的評論。 – ChrisF

回答

19

您正在尋找Enum.GetUnderlyingType(enumType);從MSDN

樣品:

static object GetAsUnderlyingType(Enum enval) 
{ 
    Type entype = enval.GetType(); 

    Type undertype = Enum.GetUnderlyingType(entype); 

    return Convert.ChangeType(enval, undertype); 
} 
+0

很簡單,謝謝。 – Will

3
using System; 

class Program 
{ 
    enum IntEnum : int { A } 

    static void Main(string[] args) 
    { 
     var intEnum = IntEnum.A; 

     Console.WriteLine(intEnum.GetType().GetEnumUnderlyingType()); 

     Console.WriteLine("Press any key to exit..."); 
     Console.ReadKey(); 
    }  
}