枚举和常量.什么时候用哪个? [英] Enums and Constants. Which to use when?

查看:71
本文介绍了枚举和常量.什么时候用哪个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读枚举时发现它们与声明常量非常相似.我怎么知道什么时候使用常量而不是枚举,反之亦然.使用枚举有哪些优点?

I was doing some reading on enums and find them very similar to declaring constants. How would I know when to use a constant rather than an enum or vice versa. What are some of the advantages of using enums?

推荐答案

当您想定义某个值的范围时,请使用枚举.颜色是一个明显的例子,如:

Use enums when you want to define a range of values that something can be. Colour is an obvious example like:

public enum Colour
{
    White,
    Red,
    Blue
}

或者可能是一组可能的事情,例如:(我从这里偷来的例子,因为我很懒)

Or maybe a set of possible things like: (Example I stole from here as I'm lazy)

[FlagsAttribute]
enum DistributedChannel
{
  None = 0,
  Transacted = 1,
  Queued = 2,
  Encrypted = 4,
  Persisted = 16,
  FaultTolerant = Transacted | Queued | Persisted
}

常量应该用于单个值,例如 PI.没有 PI 值的范围,只有 PI.

Constants should be for a single value, like PI. There isn't a range of PI values, there is just PI.

其他需要考虑的点是:

  • a:常量不一定表示常量之间的关系,而枚举表示某些东西可以是枚举定义的集合之一.
  • b:定义的枚举在用作参数时可以帮助您进行类型检查.常量只是值,因此它们不提供任何额外的语义信息.

这篇关于枚举和常量.什么时候用哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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