public enum Animal
{
Dog = 1,
Cat = 2,
Cow = 3
}
int animalID = 4;
if ((Animal)animalID == Animal.Dog) // does not throw exception
无法将animalID强制转换为Animal
。
当将枚举类型转换为整数失败时,为什么我没有收到InvalidCastException
?
public enum Animal
{
Dog = 1,
Cat = 2,
Cow = 3
}
int animalID = 4;
if ((Animal)animalID == Animal.Dog) // does not throw exception
无法将animalID强制转换为Animal
。
当将枚举类型转换为整数失败时,为什么我没有收到InvalidCastException
?
因为这不是无效的转换。
你要转换的值对于该枚举类型(在这种情况下)超出了范围,但它并非无效。
由于枚举类型的批准类型是byte、sbyte、short、ushort、int、uint、long或ulong,从整数到枚举的转换是完全合法的。
这是一种预期的行为,而且非常有用。请考虑使用带有 [Flag] 属性定义的枚举。
顺便说一下,这是一个重复问题,参见Casting an out-of-range number to an enum in C# does not produce an exception。
更多答案可能在那里 :)