获取枚举的基础/派生类型?

时间:2011-03-14 22:58:04

标签: c#

如何获取枚举的底层/派生类型(byte,short,int等)?

2 个答案:

答案 0 :(得分:20)

您正在寻找Enum.GetUnderlyingType(enumType);

来自MSDN的示例:

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

    Type undertype = Enum.GetUnderlyingType(entype);

    return Convert.ChangeType(enval, undertype);
}

答案 1 :(得分:4)

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();
    }       
}