参见英文答案 >
Cast int to enum in C#21个
如果我有这个代码
如果我有这个代码
//Spice Enums enum SpiceLevels {None = 0,Mild = 1,Moderate = 2,FerocIoUs = 3};
解决方法
只需将整数转换为枚举:
SpiceLevels level = (SpiceLevels) 3;
当然,另一种方式也有效:
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