另一个枚举与int [英] Another enum vs. int

查看:74
本文介绍了另一个枚举与int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要命名空间范围内的竞争者。
所以我可以选择使用枚举,例如:

I need namespace-wide contants. So I have the option to use enums, like:

public enum Token
{
    INFORMATIONAL,
    WARNING,
    ABORT,
    FATAL
};

但是缺点是,例如在WPF中,我现在需要将它们转换为int那么

But the disadvantage is, in WPF for example, that I need to convert them to int, now and then.

所以我想,为什么不

public static class Token 
{
    public const int
    INFORMATIONAL = 0,
    WARNING =1,
    ABORT = 2,
    FATAL = 3;
};

在源代码中,它们看起来相同而且我没有转换问题。
那么,枚举的根本原因是什么?
我显然错过了一些东西。
枚举的原因是什么?

in the source, they look the same AND I have no conversion issues. So what would be the reason for enums at all? I'm clearly missing something. What is the reason for enums?

推荐答案

考虑

使用枚举定义一个具有一些常量的类型,这些常量本身就是类型化的(不是好话,我不知道怎么说)。

With enum you define a type having some constants themselves "typed" (not the good word by I don't know how to say that).

使用枚举值和常量之间的优点是能够解析值并将枚举范围用作类型。

The advantage between using enum values and constants is to be able to parse the values and to use the enum scope as a type.

因此,这是一个更好的选择

So it is a better abstraction.

即使您可以,也不必定义值。

Also you don't need to care to define the values even if you can.

示例:

解析枚举值

foreach ( var value in Enum.GetValues(typeof(Token) ) ...

传递枚举参数

void Method(Token token) ...

声明以枚举为键的集合

var map = new Dictionary<Token, string>();

条件测试

if ( value == Token.INFORMATIONAL ) ...

简单位标志用法

https://docs.microsoft.com/zh-cn/dotnet/api/system.flags属性

默认项目名称ToString结果

Console.WriteLine(Token.INFORMATIONAL)

将显示值的名称,而不是常量的值。

Will display the name of the value, not its value as for a constant.

因此显示值:

Console.WriteLine((int)Token.INFORMATIONAL)

结论

使用常量,您需要使用反射来解析列表,但是它很丑陋,根本没有用,您不能将它们作为类型化参数传递。

With constants, you need to use reflexion to parse a list but it is ugly and not usefull at all and you can't pass them as a typed parameter.

常量的使用可能性是有限的。

Usage possibilities of constants is limited.

因此,枚举和常量根本就不是同一件事

So enums and constants are not the same thing at all even the basic as int usage.

因此,使用枚举或常量取决于您要使用的用法。

Thus using enum or constants depends on the usage you will do.

如果只关心类型安全并且需要做高级的事情,请选择枚举。

If you care about type safety and need to do advanced things, choose enum.

要说的最后一句话是,枚举并不关心基础值,因此,如果需要使用值,请使用常量,否则使用枚举。

One last word to say is that enum is to not care about the underlying value, so if you need to work with values, use constants, else enum.

使用最自然的东西。

这篇关于另一个枚举与int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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