加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C# – 你能用数值调用枚举吗?

发布时间:2020-12-15 08:45:35 所属栏目:百科 来源:网络整理
导读:参见英文答案 Cast int to enum in C#21个 如果我有这个代码 //Spice Enumsenum SpiceLevels {None = 0,Mild = 1,Moderate = 2,Ferocious = 3}; 其中陈述了枚举名称的数量,如何从变量中调用枚举,如果变量是3,我如何调用它并显示凶猛? 解决方法 只需将整数转
参见英文答案 > Cast int to enum in C#21个
如果我有这个代码
//Spice Enums
enum SpiceLevels {None = 0,Mild = 1,Moderate = 2,Ferocious = 3};

其中陈述了枚举名称的数量,如何从变量中调用枚举,如果变量是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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读