【问题标题】:Casting to invalid enum value, Enum.ToObject, does not throw exception, sets Enum to int转换为无效枚举值 Enum.ToObject 不会引发异常,将 Enum 设置为 int
【发布时间】:2014-12-09 18:58:25
【问题描述】:

这是正常行为吗?

编写一个枚举类型转换

1) 尝试文本解析 2) 回退到 int 解析。

int 解析永远不会抛出错误...

尝试在 LinqPad 中运行以下脚本,我没有测试过除了 linqpad 之外的其他编译器,但我怀疑这是 Linqpad 的问题。

如果 int 匹配失败,我该如何抛出错误?

void Main()
{
    FieldAttributes fieldattributeenum = FieldAttributes.Assembly;
    B b = B.Valx1;      
    b.Dump("B = "+((int)b).ToString()); //Valx1 (11);

    fieldattributeenum.Dump("fieldattributeenum = " +((int)fieldattributeenum).ToString()); //Assembly (3)

    b = (B) Enum.ToObject(typeof(B), (int) fieldattributeenum); 
    b.Dump("B = "+((int)b).ToString()); //valcorrect3 (3)
    A a = (A) Enum.ToObject(typeof(A), (int) fieldattributeenum); //
    a.Dump("A = "+ ((int)a).ToString()); // ??? (3) 
}

public enum B{  
    Valx1=11,
    Valx2=12,
    Valx3=13,
    Valx4=14,
    valcorrect3 = 3
}
public enum A{  
    Valx1=11,
    Valx2=12,
    Valx3=13,
    Valx4=14,
    valcorrect3
}

【问题讨论】:

    标签: c# .net casting enums linqpad


    【解决方案1】:

    只需使用Enum.IsDefined。基本上枚举只是整数,即使未定义枚举,您也可以将任何整数分配给枚举。

    if(!Enum.IsDefined(typeof(A), a))
    {
        throw new InvalidCastException("Not a valid value for A: " + a);
    }
    

    【讨论】:

    • 谢谢,我想我应该有 RTFM :)
    【解决方案2】:

    来自 MSDN Enum.ToObject Method (Type, Int32)

    ToObject(Type, Int32) 方法将值转换为枚举 基础价值为价值的成员。请注意,转换 即使 value 超出 enumType 成员的范围,也会成功。到 确保 value 是 enumType 的有效基础值 枚举,将其传递给 IsDefined 方法。

    这是设计使然。

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多