c# – 枚举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值得到特殊待遇在这样的情况?

解决方法

是的,文字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.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...