将枚举转换为整数
我有以下枚举
public enum TESTENUM
{
Value1 = 1,
Value2 = 2
}
,然后我想用它来与我拥有的整数变量进行比较,如下所示:
if ( myValue == TESTENUM.Value1 )
{
}
但是为了进行此测试,我必须按如下方式转换枚举(或者大概将整数声明为枚举类型):
if ( myValue == (int) TESTENUM.Value1 )
{
}
有没有一种方法可以告诉编译器枚举是一系列整数,这样我就不必进行此转换或重新定义变量?
I have the following enum
public enum TESTENUM
{
Value1 = 1,
Value2 = 2
}
I then want to use this to compare to an integer variable that I have, like this:
if ( myValue == TESTENUM.Value1 )
{
}
But in order to do this test I have to cast the enum as follows (or presumably declare the integer as type enum):
if ( myValue == (int) TESTENUM.Value1 )
{
}
Is there a way that I can tell the compiler that the enum is a series of integers, so that I don’t have to do this cast or redefine the variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,您需要转换枚举值。如果您不想进行强制转换,请考虑使用具有常量 int 值的类:
但是,这样做有一些缺点;缺乏类型安全性是使用枚举的一个重要原因。
No. You need to cast the enum value. If you don't want to cast, then consider using a class with constant int values:
However, there are some downsides to this; the lack of type safety being a big reason to use the
enum
.您可以告诉枚举它包含整数:
但是您仍然必须手动转换它们,
You can tell the enum that it contains integers:
However you have to still cast them manually,
请记住,在上下文中转换枚举值正是如何告诉编译器“看这里,我知道这个枚举值是 int 类型,所以就这样使用它”。
Keep in mind that casting the enum value in your context is exactly how you tell the compiler that "look here, I know this enum value to be of type int, so use it as such".
不,没有(与 C++ 不同),并且出于类型安全的充分理由。
No there isn't (unlike C++), and for a good reason of type safety.