没有enum-int的运算符,但对于enum-0?

时间:2015-07-15 08:24:53

标签: c# enums operators

我想解析一个二进制文件。

我有3种有效的格式。在二进制文件中,格式由short表示。但它只能是0,1,2

我创建了枚举来描述这些格式。

当我编写此代码时,我看到了这个编译错误:

运营商'>'无法应用于enumint的操作数。

    public enum FormatType
    {
        Type0 = 0,
        Type1 = 1,
        Type2 = 2
    }

    private FormatType _format;
    public FormatType Format
    {
        get { return _format; }
        set
        {
            // red line under value > 2.
            if (value < 0 || value > 2) throw new FileParseException(ParseError.Format);
            _format = value;
        }
    }

value < 0没有问题。

稍后我发现我可以将enum与0进行比较,但不能与其他数字进行比较。

只是为了解决这个问题,我可以将int转换为枚举。

value > (FormatType)2

但是在与0比较时没有必要施展为什么?

value < 0

1 个答案:

答案 0 :(得分:2)

您需要将枚举转换为int,将其用作int:

    public FormatType Format
    {
        get { return _format; }
        set
        {
            // red line under value > 2.
            if (value < 0 || (int)value > 2) throw new FileParseException(ParseError.Format);
            _format = value;
        }
    }

编辑: 文字零将始终隐式转换为任何枚举,以确保您能够将其初始化为其默认值(即使没有值为0的枚举)

找到可以更好地解释它的链接:

http://blogs.msdn.com/b/ericlippert/archive/2006/03/29/the-root-of-all-evil-part-two.aspx http://blogs.msdn.com/b/ericlippert/archive/2006/03/28/563282.aspx

相关问题