c# – 枚举0值不一致

前端之家收集整理的这篇文章主要介绍了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.

原文链接:https://www.f2er.com/csharp/95849.html

猜你在找的C#相关文章