示例代码:
public enum Foods { Burger,Pizza,Cake } private void button1_Click(object sender,EventArgs e) { Eat(0); // A Eat((Foods)0); // B //Eat(1); // C : won't compile : cannot convert from 'int' to 'Foods' Eat((Foods)1); // D } private void Eat(Foods food) { MessageBox.Show("eating : " + food); }
C行的代码不会编译,但是A行编译很好.
有没有什么特别的枚举与0值得到特殊待遇在这样的情况?
解决方法
是的,文字0可隐式转换为任何枚举类型,并表示该类型的默认值.根据C#语言规范,特别是关于枚举的1.10节:
The default value of any enum type is the integral value zero converted to the enum type. In cases where variables are automatically initialized to a default value,this is the value given to variables of enum types. In order for the default value of an enum type to be easily available,the literal 0 implicitly converts to any enum type. For the default value of an enum type to be easily available,the literal 0 implicitly converts to any enum type.