Casting ints to enums in C#

前端 未结 12 2125
北荒
北荒 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:50

    Guessing about 'why' is always dangerous, but consider this:

    enum Direction { North =1, East = 2, South = 4, West = 8 }
    Direction ne = Direction.North | Direction.East;
    
    int value = (int) ne; // value == 3
    string text = ne.ToString();  // text == "3"
    

    When the [Flags] attribute is put in front of the enum, that last line changes to

    string text = ne.ToString();  // text == "North, East"
    

提交回复
热议问题