枚举和常量。 什么时候使用哪个?
我正在阅读一些关于枚举的文章,发现它们与声明常量非常相似。 我怎么知道何时使用常量而不是枚举,反之亦然。 使用枚举有哪些优点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
当您想要定义某个值的范围时,请使用枚举。 颜色是一个明显的例子,例如:
或者可能是一组可能的事物,例如:
(例如我从这里偷来的,因为我很懒)
常量应该是单个值,如 PI。 没有 PI 值的范围,只有 PI。
其他需要考虑的要点是:
Use enums when you want to define a range of values that something can be. Colour is an obvious example like:
Or maybe a set of possible things like:
(Example I stole from here as I'm lazy)
Constants should be for a single value, like PI. There isn't a range of PI values, there is just PI.
Other points to consider are:
其他答案中缺少的是枚举具有整数基本类型。 您可以将默认值从 int 更改为除 char 之外的任何其他整型类型,例如:
您可以从基本类型显式转换或隐式转换为基本类型,这在 switch 语句中很有用。 请注意,即使枚举没有具有适当值的成员,也可以将基类型的任何值转换为枚举。 因此,始终使用开关中的默认部分是一个好主意。 顺便说一句,.NET 本身甚至允许浮点值枚举,但你不能在 C# 中定义它们,尽管我认为你仍然可以使用它们(除了在 switch 中)。
此外,使用枚举可以提高类型安全性。 如果您打算使用 int 常量作为方法参数,那么我可以使用任何 int 值调用该方法。 当然,通过强制转换,枚举也可能发生这种情况,但它不会意外发生。 更糟糕的是可能会混淆参数的顺序。
如果常量 A 只能进入 a,常量 B 只能进入 b,那么使用两种不同的枚举类型将在编译期间发现任何误用。
What's missing from the other answers is that enums have an integer base type. You can change the default from int to any other integral type except char like:
You can cast explicitly from and implicitly to the the base type, which is useful in switch-statements. Beware that one can cast any value of the base type to an enum, even if the enum has no member with the appropriate value. So using always the default section in a switch is a good idea. BTW, .NET itself allows even floating point valued enums, but you can't define them in C#, although I think you can still use them (except in switch).
Furthermore, using enums gives you more type safety. If you intend to use e.g. int constants as method parameters, then I could call the method with any int value. Granted, via casting it can happen with enums, too, but it won't happen accidentally. Worse is the possibility to confuse the order of parameters.
If constant A only may go into a and constant B only may go into b, then using two different enum types will uncover any misuse during the compilation.
常量是一种语言功能,它表示变量不会更改值(因此编译器可以围绕该知识进行优化),其中枚举是特定类型。
常量可以是任何数据类型,但枚举就是枚举。
我在任何可以有多个选项并希望提高代码可读性的地方使用枚举。 即,您可以将跟踪级别作为值为 0、1、2 的 int 或作为错误、警告和信息的枚举。
枚举还可以用作按位运算符,即 FontStyle.Bold | FontStyle.Italic 将为您提供粗体和斜体字体。
A constant is a language feature which says that the variable won't change value (so the compiler can do optimisations around that knowledge) where an enum is a specific type.
Constants can be any data type but an enum is an enum.
I use an enum any place where you could have a number of options and want to improve readability of the code. i.e. you could have trace levels as an int with values 0, 1, 2 or as an enum as error, warning and info.
Enum's also have the ability to be used as bitwise operators, i.e. FontStyle.Bold | FontStyle.Italic would give you bold and italic fonts.
除了罗伯特的回答之外:
使用枚举来表示一组有限的命名值。 您并不真正关心每个符号背后的数值(但您仍然可以强加它们,例如为了与遗留系统兼容)。
罗伯特:是的,枚举可以用作位字段。 使用 Flags 属性(并确保枚举成员具有合适的数值)。
In addition to Robert's answer:
Use enum for a finite set of named values. You don't really care about the numerical value behind each symbol (but you still have the ability to impose them, e.g. for compatibility with a legacy system).
Robert: Yes, Enum's can be used as bit fields. Use the Flags attribute (and make sure members of the enum have suitable numerical values).
我发现使用
enum
而不是const
时方便的一件事是,您可以迭代enum
中的值,但这样做要困难得多带有const
值。One thing I find handy when using
enum
instead ofconst
is that you can iterate through the values in anenum
, it's much harder to do that withconst
values.C# 常量与变量类似,它为值提供定义的名称。 但是,常量与标准变量不同,因为一旦定义,分配给常量的值就永远不能更改。 常量的主要好处是它们有助于创建自记录代码以及允许在单个位置声明键值,这样在需要更新值和重新编译软件时可以轻松维护。
而枚举器列表对于定义序列和状态非常有用,特别是当这些状态自然进展时。 这是因为列表中的每个常量都可以使用其名称或值进行格式化和比较。 枚举还可以用于定义一组有限的有效值。
A C# constant is similar to a variable in that it gives a defined name to a value. However, a constant differs from a standard variable because once defined, the value assigned to the constant can never be changed. The chief benefit of constants is their assistance in creating self-documenting code as well as allowing the declaration of key values in a single place, which permits easy maintenance should the value need to be updated and the software recompiled.
Whereas Enumerator lists are useful for defining sequences and states, particularly when there is a natural progression through those states. This is because each constant in the list can be formatted and compared using either its name or value. An enum can also be used to define a limited set of valid values.
如果您需要基于整数的值,请使用枚举。
如果您需要基于字符串的值,请使用带有常量的结构。
当你有类似的东西时
If you need integer based values use enums.
If you need string based values use structs with Constants.
When you have something like
如果您有一组不应该更改的预定义选项(即添加更多选项等),请使用枚举,否则为 const。
考虑以下事项:
因此,使用 const 可以允许您传递 const 声明中未定义的参数值,即。 3 表示乘法,4 表示除法。 这是好还是坏取决于您的逻辑,有时允许用户传递任意值并收到意外结果是不明智的。
If you have a set of predefined choices which is not supposed to change (i.e adding more choices etc.) than use enum otherwise consts.
Consider the following:
so, using
const
can allow you to pass a parameter value not defined inconst
declaration, ie. 3 for multiply and 4 for divide. This is good or bad depends on your logic, sometimes it is not wise to allow the user to pass arbitrary values and receive unexpected result.