Casting ints to enums in C#

前端 未结 12 2119
北荒
北荒 2020-12-05 02:30

There is something that I cannot understand in C#. You can cast an out-of-range int into an enum and the compiler does not flinch. Imagine this

12条回答
  •  执笔经年
    2020-12-05 02:55

    I certainly see Cesar's point, and I remember this initially confused me too. In my opinion enums, in their current implementation, are indeed a little too low level and leaky. It seems to me that there would be two solutions to the problem.

    1) Only allow arbitrary values to be stored in an enum if its definition had the FlagsAttribute. This way, we can continue to use them for a bitmask when appropriate (and explicitly declared), but when used simply as placeholders for constants we would get the value checked at runtime.

    2) Introduce a separate primitive type called say, bitmask, that would allow for any ulong value. Again, we restrict standard enums to declared values only. This would have the added benefit of allowing the compiler to assign the bit values for you. So this:

    [Flags]
    enum MyBitmask
    { 
        FirstValue = 1, SecondValue = 2, ThirdValue = 4, FourthValue = 8 
    }
    

    would be equivalent to this:

    bitmask MyBitmask
    {
        FirstValue, SecondValue, ThirdValue, FourthValue 
    }
    

    After all, the values for any bitmask are completely predictable, right? As a programmer, I am more than happy to have this detail abstracted away.

    Still, too late now, I guess we're stuck with the current implementation forever. :/

提交回复
热议问题