【问题标题】:Why don't I get InvalidCastException when casting enum to integer fails?将枚举转换为整数失败时,为什么我没有收到 InvalidCastException?
【发布时间】:2011-02-17 09:02:22
【问题描述】:
public enum Animal
{
    Dog = 1,
    Cat = 2,
    Cow = 3
}

int animalID = 4;
if ((Animal)animalID == Animal.Dog) // does not throw exception

animalID 不能转换为 Animal
将枚举转换为整数失败时,为什么我没有得到InvalidCastException

【问题讨论】:

标签: c# .net enums


【解决方案1】:

因为它不是无效的演员表。

您正在投射的值是 超出范围的枚举(在这种情况下),但它不是无效的。

由于已批准的枚举类型是 byte、sbyte、short、ushort、int、uint、long 或 ulong,因此从整数到枚举的强制转换是完全合法的。

Source - MSDN

【讨论】:

    【解决方案2】:

    这是一种预期行为,非常有用。考虑使用 [Flag] 属性定义的枚举。

    顺便说一句,这是一个骗局 Casting an out-of-range number to an enum in C# does not produce an exception

    可能会有更多答案:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多