如果我有这个代码
//Spice Enums
enum SpiceLevels {None = 0 , Mild = 1, Moderate = 2, Ferocious = 3};
哪个状态是枚举名称+它们的编号,我如何从变量调用枚举,比如说,如果变量是3
,我如何让它调用并显示Ferocious?
只需将整数强制转换为枚举:
SpiceLevels level = (SpiceLevels) 3;
当然,另一种方法也有效:
int number = (int) SpiceLevels.Ferocious;
另请参阅MSDN:
每个枚举类型都有一个底层类型,可以是除char之外的任何整数类型。枚举元素的默认底层类型是int。
但是,从枚举类型转换为整型需要显式强制转换
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值强制转换为枚举的一种情况。。。
int myValue = 3;
SpiceLevels level = (SpiceLevels)myValue;
WriteLine(level); // writes "Ferocious"