关于C#:你能按数字值调用枚举吗?


C# - Can you call an Enum by the number value?

本问题已经有最佳答案,请猛点这里访问。

如果我有这个密码

1
2
//Spice Enums
enum SpiceLevels {None = 0 , Mild = 1, Moderate = 2, Ferocious = 3};

哪些状态的枚举名称+它们的编号,我如何从一个变量调用一个枚举,比如如果一个变量是3,我如何让它调用和显示凶猛的?


只需将整数强制转换为枚举:

1
SpiceLevels level = (SpiceLevels) 3;

当然,另一种方法也有效:

1
int number = (int) SpiceLevels.Ferocious;

也见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


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


默认情况下,枚举从Int32继承,因此每个项都被分配一个从零开始的数值(除非您自己指定了值,如您所做)。

因此,获取枚举只是将int值强制转换为枚举的一种情况…

1
2
3
int myValue = 3;
SpiceLevels level = (SpiceLevels)myValue;
WriteLine(level); // writes"Ferocious"