How can I cast int to enum?

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

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

30条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 01:02

    Below is a nice utility class for Enums

    public static class EnumHelper
    {
        public static int[] ToIntArray(T[] value)
        {
            int[] result = new int[value.Length];
            for (int i = 0; i < value.Length; i++)
                result[i] = Convert.ToInt32(value[i]);
            return result;
        }
    
        public static T[] FromIntArray(int[] value) 
        {
            T[] result = new T[value.Length];
            for (int i = 0; i < value.Length; i++)
                result[i] = (T)Enum.ToObject(typeof(T),value[i]);
            return result;
        }
    
    
        internal static T Parse(string value, T defaultValue)
        {
            if (Enum.IsDefined(typeof(T), value))
                return (T) Enum.Parse(typeof (T), value);
    
            int num;
            if(int.TryParse(value,out num))
            {
                if (Enum.IsDefined(typeof(T), num))
                    return (T)Enum.ToObject(typeof(T), num);
            }
    
            return defaultValue;
        }
    }
    

提交回复
热议问题