Why don't I get InvalidCastException when casting enum to integer fails?

匿名 (未验证) 提交于 2019-12-03 08:41:19

问题:

public enum Animal {     Dog = 1,     Cat = 2,     Cow = 3 }  int animalID = 4; if ((Animal)animalID == Animal.Dog) // does not throw exception

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

回答1:

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.

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.

Source - MSDN



回答2:

This is an intended behaviour and can be pretty useful. Consider enums defined with the [Flag] attribute.

btw, this is a dupe of Casting an out-of-range number to an enum in C# does not produce an exception

more answers may be in there :)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!