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

Wil*_*ill 13 c#

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

Bro*_*ass 20

你在找Enum.GetUnderlyingType(enumType);

来自MSDN的示例:

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

    Type undertype = Enum.GetUnderlyingType(entype);

    return Convert.ChangeType(enval, undertype);
}
Run Code Online (Sandbox Code Playgroud)


Gra*_*mas 5

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();
    }       
}
Run Code Online (Sandbox Code Playgroud)