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,因此从整数到枚举的转换是完全合法的。
关于c# - 为什么在将枚举转换为整数失败时我没有得到 InvalidCastException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5026876/