将枚举转换为int是否可以 [英] Is it ok to cast enum to int

查看:298
本文介绍了将枚举转换为int是否可以的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以将int转换为这样的枚举:



Hi, is it ok to cast int to enum like this:

itemID = (MyEnumType)results.value("itemID").toInt();





其中itemID的类型为MyEnumType,右侧是整数。



where itemID is of type MyEnumType-and right hand side is integer.

推荐答案

对于编译器来说没问题。虽然您可能想要熟悉C ++ 11,它允许定义非基于int的枚举。



为了良好的编码,它是不是ok,但是:强制转换几乎总是用来治疗变量,函数参数或函数返回类型的错误选择。否则可能是糟糕的课堂设计。如果您可以修复函数,变量或类以使用不需要强制转换的类型,那么这将永远是首选解决方案。
For the compiler it is ok. Although you might want to familiarize yourself with C++11, which allows the definition of enums that are not int-based.

For good coding, it is not "ok", however: casting is almost always used as a cure for a bad choice of variable, function argument or function return type. Or else it may be a case of bad class design. If you can fix the function, variable or class to use a type that doesn''t require casting, that will always be the preferred solution.


答案是肯定的。您可以按如下方式执行此操作

The answer is Yes. You simply can do it as follows
public enum  Country
{
    Bangladesh = 1,
    India = 2
}

public static void Main(string[] args)
{
    Country e = Country.Bangladesh;

    int x = (int) e;

    Country e2 = (Country) x;

    Console.ReadKey();
}


这是枚举的一个不幸功能。没有从任何东西到枚举的优雅转换。你做它的方式看起来很难看,但除了一个重复所有枚举值的大讨厌的switch()语句之外,它几乎是唯一的方法。
This is one of the unfortunate features of enums. There is no elegant conversion from ''anything'' to enum. The way you are doing it looks ugly but is pretty much the only way besides a big nasty switch() statement that duplicates all of the enum values.


这篇关于将枚举转换为int是否可以的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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