将枚举转换为整数

发布于 2024-09-06 16:53:29 字数 364 浏览 3 评论 0原文

我有以下枚举

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

抽个烟儿 2024-09-13 16:53:29

不,您需要转换枚举值。如果您不想进行强制转换,请考虑使用具有常量 int 值的类:

class static EnumLikeClass
{
    public const int Value1 = 1;
    public const int Value2 = 2;
}

但是,这样做有一些缺点;缺乏类型安全性是使用枚举的一个重要原因。

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;
}

However, there are some downsides to this; the lack of type safety being a big reason to use the enum.

来世叙缘 2024-09-13 16:53:29

您可以告诉枚举它包含整数:

public enum TESTENUM: int
{
    Value1 = 1,
    Value2 = 2
}

但是您仍然必须手动转换它们,

You can tell the enum that it contains integers:

public enum TESTENUM: int
{
    Value1 = 1,
    Value2 = 2
}

However you have to still cast them manually,

2024-09-13 16:53:29

请记住,在上下文中转换枚举值正是如何告诉编译器“看这里,我知道这个枚举值是 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".

皇甫轩 2024-09-13 16:53:29

不,没有(与 C++ 不同),并且出于类型安全的充分理由。

No there isn't (unlike C++), and for a good reason of type safety.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文