如果我有这段代码
//Spice Enums
enum SpiceLevels {None = 0 , Mild = 1, Moderate = 2, Ferocious = 3};
枚举名称+编号,如何从变量调用枚举?例如,如果一个变量是3
,如何让它调用并显示"Ferocious"?
如果我有这段代码
//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"