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

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

问题描述

目前是没有这样做,数据丢失,有啥为被显式转换枚举到整型的原因是什么?

这岂不是如果它是隐含的更直观,说,当你有一个像更高级别的方法:

  PerformOperation(OperationType.Silent型)
 

其中, PerformOperation 调用的裸这样一个包裹C ++方式:

  _unmanaged_perform_operation(INT operation_type)
 

解决方案

有枚举两个主要的和不一致的用途:

 枚举奖牌
{金奖,银奖,铜奖}

[国旗]
枚举FilePermissionFlags
{
    的CanRead = 0×01,
    CanWrite = 0×02,
    CanDelete = 0×04
}
 

在第一种情况下,这是没有意义的把这些东西作为数字。它们被存储为整数的事实是一个实现细节。你不能在逻辑上加,减,乘或除金,银,铜奖。

在第二种情况下,它的的是没有意义的把这些东西作为数字。你可以不加,减,乘或除他们。唯一明智的操作是位运算。

枚举是糟糕的数字,所以你不应该能够将其视为数字意外。

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 )

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天全站免登陆