【问题标题】:no operator for enum-int but for enum-0? [duplicate]enum-int 没有运算符,但 enum-0 没有运算符? [复制]
【发布时间】:2015-10-04 04:27:06
【问题描述】:

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

我有 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 &lt; 0没有问题。

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

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

value > (FormatType)2

但是为什么和0比较时不需要强制转换?

value < 0

【问题讨论】:

  • 您在寻找Enum.IsDefined(typeof(FormatType), value)吗? -- 见Enum.IsDefined
  • 感谢您的建议。我不知道我可以像这样检查枚举的存在。我用了它,但我的问题仍然存在! @Corak
  • 也许这会有所帮助:Implicit Zero To Enum Conversion --- 或多或少指向:6.1.3 Implicit enumeration conversions 声明:“隐式枚举转换允许将十进制整数文字 0 转换为任何枚举类型。”
  • 感谢 cmets 和链接。我认为问题出在操作员上。但它是 0 @Corak 的隐式转换

标签: c# enums operators


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-01-03
    • 2014-05-20
    • 2012-07-11
    • 2015-12-14
    • 2020-07-25
    • 1970-01-01
    • 2011-04-12
    • 2020-12-13
    相关资源
    最近更新 更多