English 中文(简体)
当将枚举强制转换为整数失败时,为什么不得到InvalidCastException?
原标题:Why don t I get InvalidCastException when casting enum to integer fails?
  • 时间:2011-02-17 09:02:22
  •  标签:
  • c#
  • .net
  • enums
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?

最佳回答

因为它不是无效的强制转换。

您正在强制转换的值超出了枚举的范围(在本例中),但它不是无效的。

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

来源-MSDN

问题回答

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

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

更多答案可能在那里:)





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签