转换枚举为int [英] Converting enum to int
本文介绍了转换枚举为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下枚举
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?
推荐答案
没有。你需要投枚举值。如果你不想投,那么可以考虑使用一类具有恒定的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:
class static EnumLikeClass
{
public const int Value1 = 1;
public const int Value2 = 2;
}
不过,也有一些缺点这一点;缺乏类型安全是一个很大的原因使用枚举
。
这篇关于转换枚举为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文