为什么枚举需要显式转换为 int 类型? [英] Why enums require an explicit cast to int type?

查看:29
本文介绍了为什么枚举需要显式转换为 int 类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样做不会丢失数据,那么必须将枚举显式转换为整数的原因是什么?

There is no data loss by doing this, so what's the reason for having to explicitly cast enums to ints?

如果它是隐式的,会不会更直观,比如当你有一个更高级别的方法时:

Would it not be more intuitive if it was implicit, say when you have a higher level method like:

PerformOperation ( OperationType.Silent type )

其中 PerformOperation 调用一个这样公开的封装 C++ 方法:

where PerformOperation calls a wrapped C++ method that's exposed as such:

_unmanaged_perform_operation ( int operation_type )

推荐答案

枚举有两种主要且不一致的用途:

There are two primary and inconsistent uses of enums:

enum Medals
{ Gold, Silver, Bronze }

[Flags]
enum FilePermissionFlags
{
    CanRead = 0x01,
    CanWrite = 0x02,
    CanDelete = 0x04
}

在第一种情况下,将这些东西视为数字是没有意义的.它们存储为整数的事实是一个实现细节.你不能逻辑地加、减、乘或除金、银和青铜.

In the first case, it makes no sense to treat these things as numbers. The fact that they are stored as integers is an implementation detail. You can't logically add, subtract, multiply or divide Gold, Silver and Bronze.

在第二种情况下,将这些东西视为数字是没有意义的.你不能加、减、乘或除它们.唯一合理的操作是按位操作.

In the second case, it also makes no sense to treat these things as numbers. You can't add, subtract, multiply or divide them. The only sensible operations are bitwise operations.

枚举是糟糕的数字,因此您不应该意外地将它们视为数字.

Enums are lousy numbers, so you should not be able to treat them as numbers accidentally.

这篇关于为什么枚举需要显式转换为 int 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆