Can you call an Enum by the number value?

This question already has an answer here:

  • Cast int to enum in C# 21 answers

  • Just cast the integer to the enum:

    SpiceLevels level = (SpiceLevels) 3;
    

    and of course the other way around also works:

    int number = (int) SpiceLevels.Ferocious;
    

    See also MSDN:

    Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of enumeration elements is int.

    ...

    However, an explicit cast is necessary to convert from enum type to an integral type


    enum SpiceLevels { None = 0, Mild = 1, Moderate = 2, Ferocious = 3 };
    static void Main(string[] args)
    {
        int x = 3;
        Console.WriteLine((SpiceLevels)x);
        Console.ReadKey();
    }
    

    Enums inherit from Int32 by default so each item is assigned a numeric value, starting from zero (unless you specify the values yourself, as you have done).

    Therefore, getting the enum is just a case of casting the int value to your enum...

    int myValue = 3;
    SpiceLevels level = (SpiceLevels)myValue;
    WriteLine(level); // writes "Ferocious"
    
    链接地址: http://www.djcxy.com/p/22514.html

    上一篇: 如何将int转换为枚举值?

    下一篇: 你可以通过数字值来调用Enum吗?