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.
C # 常量类似于变量,因为它为值提供定义的名称。但是,常数不同于标准变量,因为一旦定义,分配给常数的值永远不能更改。常量的主要好处是它们有助于创建自我记录的代码,以及允许在单个位置声明键值,这样在需要更新值和重新编译软件时便于维护。
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.
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:
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).
此外,使用枚举可以提供更多的类型安全性。如果您打算使用例如 int 常量作为方法参数,那么我可以使用任何 int 值调用该方法。当然,通过铸造它也可以发生在枚举,但它不会偶然发生。更糟糕的是可能会混淆参数的顺序。
void method(int a, int b) {...}
如果常量 A 只能进入 a,常量 B 只能进入 b,那么在编译过程中使用两种不同的枚举类型将会发现任何错误。
class x
{
public string string_value {get;set;}
publi int int_value {get;set;}
}
x model = new x();
model.string_value = struct.some_value;
model.int_value = enum.some_value;
public class Math
{
enum Command {none = 0, add =1, subtract = 2}
const int none =0, add=1,subtract =2;
public virtual int Operate(int a, int b, Command command)
{
if (command == Command.add) return a+b;
if(command == Command.subtract) return a-b;
return a;
}
public virtual int Operate(int a, int b, int command)
{
if (command == add) return a+b;
if(command==subtract) return a-b;
return a;
}
}`
class Math1: Math
{
public override Operate(int a, int b, int command)
{
if(command<3) return base.Operate(a, b, command)
if(command =3) return a*b;
if(command==4) return a/b;
return a;
}
}