C# 枚举和常量。什么时候用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/613837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Enums and Constants. Which to use when?
提问by Draco
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?
我正在阅读枚举,发现它们与声明常量非常相似。我怎么知道什么时候使用常量而不是枚举,反之亦然。使用枚举有哪些优点?
采纳答案by Andrew Barrett
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 hereas I'm lazy)
或者可能是一组可能的东西,例如:(例如,我很懒,所以从这里偷了东西)
[FlagsAttribute]
enum DistributedChannel
{
None = 0,
Transacted = 1,
Queued = 2,
Encrypted = 4,
Persisted = 16,
FaultTolerant = Transacted | Queued | Persisted
}
Constants should be for a single value, like PI. There isn't a range of PI values, there is just PI.
常量应该用于单个值,例如 PI。没有 PI 值的范围,只有 PI。
Other points to consider are:
其他需要考虑的点是:
- a: Constants don't indicate a relationship between the constants, whereas an enumeration indicates that something can be one of the following.
- b: Enumeration can be used in switch statements, etc. I don't think that constants can, because they have no relationship to one another.
- a:常量不表示常量之间的关系,而枚举表示某些东西可以是以下之一。
- b:枚举可以用在switch语句等中,我觉得常量不行,因为它们之间没有关系。
回答by Robert MacLean
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.
我在任何可以有多个选项并希望提高代码可读性的地方使用枚举。即您可以将跟踪级别作为值为 0、1、2 的 int 或作为错误、警告和信息的枚举。
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.
枚举还可以用作按位运算符,即 FontStyle.Bold | FontStyle.Italic 会给你粗体和斜体字体。
回答by Serge Wautier
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 Flagsattribute (and make sure members of the enum have suitable numerical values).
对一组有限的命名值使用枚举。您并不真正关心每个符号背后的数值(但您仍然可以强加它们,例如为了与遗留系统兼容)。
罗伯特:是的,枚举可以用作位域。使用Flags属性(并确保枚举成员具有合适的数值)。
回答by simplyharsh
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.
AC# 常量类似于变量,因为它为值提供了一个定义的名称。但是,常量与标准变量不同,因为一旦定义,分配给常量的值就永远无法更改。常量的主要好处是它们有助于创建自记录代码以及允许在单个位置声明键值,如果需要更新值和重新编译软件,则可以轻松维护。
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.
而枚举器列表对于定义序列和状态很有用,特别是当这些状态有自然进展时。这是因为列表中的每个常量都可以使用其名称或值进行格式化和比较。枚举也可用于定义一组有限的有效值。
回答by Johannes
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:
其他答案中缺少的是枚举具有整数基类型。您可以将默认值从 int 更改为除 char 之外的任何其他整数类型,例如:
enum LongEnum : long {
foo,
bar,
}
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).
您可以显式转换和隐式转换为基本类型,这在 switch 语句中很有用。请注意,即使枚举没有具有适当值的成员,也可以将基类型的任何值强制转换为枚举。所以总是在 switch 中使用默认部分是一个好主意。顺便说一句,.NET 本身甚至允许浮点值枚举,但您不能在 C# 中定义它们,尽管我认为您仍然可以使用它们(除了在 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.
此外,使用枚举可为您提供更多的类型安全性。如果您打算使用例如 int 常量作为方法参数,那么我可以使用任何 int 值调用该方法。当然,通过强制转换,它也可以在枚举中发生,但不会意外发生。更糟糕的是可能会混淆参数的顺序。
void method(int a, int b) {...}
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.
如果常量 A 只能进入 a 而常量 B 只能进入 b,那么使用两种不同的枚举类型将发现编译过程中的任何误用。
回答by David Klempfner
One thing I find handy when using enum
instead of const
is that you can iterate through the values in an enum
, it's much harder to do that with const
values.
我发现在使用enum
而不是时方便的一件事const
是您可以遍历 an 中的值enum
,但使用const
值来做到这一点要困难得多。