Casting ints to enums in C#

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

    Thought I'd share the code I ended up using to validate Enums, as so far we don't seem to have anything here that works...

    public static class EnumHelper
    {
        public static bool IsValidValue(int value)
        {
            try
            {
                Parse(value.ToString());
            }
            catch
            {
                return false;
            }
    
            return true;
        }
    
        public static T Parse(string value)
        {
            var values = GetValues();
            int valueAsInt;
            var isInteger = Int32.TryParse(value, out valueAsInt);
            if(!values.Select(v => v.ToString()).Contains(value)
                && (!isInteger || !values.Select(v => Convert.ToInt32(v)).Contains(valueAsInt)))
            {
                throw new ArgumentException("Value '" + value + "' is not a valid value for " + typeof(T));
            }
    
            return (T)Enum.Parse(typeof(T), value);
        }
    
        public static bool TryParse(string value, out T p)
        {
            try
            {
                p = Parse(value);
                return true;
            }
            catch (Exception)
            {
                p = default(T);
                return false;
            }
    
        }
    
        public static IEnumerable GetValues()
        {
            return Enum.GetValues(typeof (T)).Cast();
        }
    }
    

提交回复
热议问题