Get underlying/derived type of enum?

前端 未结 2 1980
甜味超标
甜味超标 2020-12-16 15:10

How can you get the underlying/derived Type(byte, short, int, etc) of an enum?

相关标签:
2条回答
  • 2020-12-16 15:51

    You are looking for Enum.GetUnderlyingType(enumType);

    Sample from MSDN:

    static object GetAsUnderlyingType(Enum enval)
    {
        Type entype = enval.GetType();
    
        Type undertype = Enum.GetUnderlyingType(entype);
    
        return Convert.ChangeType(enval, undertype);
    }
    
    0 讨论(0)
  • 2020-12-16 15:56
    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();
        }       
    }
    
    0 讨论(0)
提交回复
热议问题