How can I cast int to enum?

后端 未结 30 2022
礼貌的吻别
礼貌的吻别 2020-11-22 00:56

How can an int be cast to an enum in C#?

30条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 01:06

    I don't know anymore where I get the part of this enum extension, but it is from stackoverflow. I am sorry for this! But I took this one and modified it for enums with Flags. For enums with Flags I did this:

      public static class Enum where T : struct
      {
         private static readonly IEnumerable All = Enum.GetValues(typeof (T)).Cast();
         private static readonly Dictionary Values = All.ToDictionary(k => Convert.ToInt32(k));
    
         public static T? CastOrNull(int value)
         {
            T foundValue;
            if (Values.TryGetValue(value, out foundValue))
            {
               return foundValue;
            }
    
            // For enums with Flags-Attribut.
            try
            {
               bool isFlag = typeof(T).GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0;
               if (isFlag)
               {
                  int existingIntValue = 0;
    
                  foreach (T t in Enum.GetValues(typeof(T)))
                  {
                     if ((value & Convert.ToInt32(t)) > 0)
                     {
                        existingIntValue |= Convert.ToInt32(t);
                     }
                  }
                  if (existingIntValue == 0)
                  {
                     return null;
                  }
    
                  return (T)(Enum.Parse(typeof(T), existingIntValue.ToString(), true));
               }
            }
            catch (Exception)
            {
               return null;
            }
            return null;
         }
      }
    

    Example:

    [Flags]
    public enum PetType
    {
      None = 0, Dog = 1, Cat = 2, Fish = 4, Bird = 8, Reptile = 16, Other = 32
    };
    
    integer values 
    1=Dog;
    13= Dog | Fish | Bird;
    96= Other;
    128= Null;
    

提交回复
热议问题