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

no operator for enum-int but for enum-0?

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

我有 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没有问题。

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

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

value > (FormatType)2

但是与0比较时不需要转换为什么?

value < 0

您需要将枚举转换为 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