以整数失败铸造枚举时,为什么我没有拿到InvalidCastException的? [英] Why don't I get InvalidCastException when casting enum to integer fails?

查看:152
本文介绍了以整数失败铸造枚举时,为什么我没有拿到InvalidCastException的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public enum Animal
{
    Dog = 1,
    Cat = 2,
    Cow = 3
}

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

animalID不能被强制转换为动物
为什么我没有拿到 InvalidCastException的铸造枚举时整不成?

animalID can't be casted to Animal.
Why don't I get InvalidCastException when casting enum to integer fails?

推荐答案

由于它不是一个无效的转换。

Because it's not an invalid cast.

正在铸造的值的出于对枚举(在这种情况下)范围的,但它不是无效的。

The value you are casting is out of range for the enum (in this case) but it's not invalid.

由于批准类型枚举是字节,为sbyte,总之,USHORT,INT,UINT,长,或ULONG强制转换整数到枚举是完全合法的。

As the approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong a cast from integer to enum is perfectly legal.

来源 - MSDN

这篇关于以整数失败铸造枚举时,为什么我没有拿到InvalidCastException的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆