本文介绍了枚举0值不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例代码:
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值,有特殊的治疗在这种情况下吗?
Code at line C won't compile, but line A compiles fine.Is there something special about an enum with 0 value that gets it special treatment in cases like this ?
推荐答案
是的,字面值0可隐式转换为任何枚举类型,并表示该类型的默认值。根据C#语言规范,特别是关于枚举的1.10节:
Yes, the literal 0 is implicitly convertible to any enum type and represents the default value for that type. According to the C# language specification, in particular section 1.10 on enums:
这篇关于枚举0值不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!