Casting ints to enums in C#

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

    That is unexpected... what we really want is to control the casting... for instance:

    Colour eco;
    if(Enum.TryParse("17", out eco)) //Parse successfully??
    {
      var isValid = Enum.GetValues(typeof (Colour)).Cast().Contains(eco);
      if(isValid)
      {
         //It is really a valid Enum Colour. Here is safe!
      }
    }
    

提交回复
热议问题