How to get an array of all enum values in C#?

前端 未结 10 2115
刺人心
刺人心 2020-12-05 01:48

I have an enum that I\'d like to display all possible values of. Is there a way to get an array or list of all the possible values of the enum instead of manually creating s

10条回答
  •  猫巷女王i
    2020-12-05 02:00

    If you prefer a more generic way, here it is. You can add up more converters as per your need.

        public static class EnumConverter
        {
    
            public static string[] ToNameArray()
            {
                return Enum.GetNames(typeof(T)).ToArray();
            }
    
            public static Array ToValueArray()
            {
                return Enum.GetValues(typeof(T));
            }
    
            public static List ToListOfValues()
            {
                return Enum.GetValues(typeof(T)).Cast().ToList();
            }
    
    
            public static IEnumerable ToEnumerable()
            {
                return (T[])Enum.GetValues(typeof(T));
            }
    
        }
    

    Sample Implementations :

       string[] roles = EnumConverter.ToStringArray();
       List roles2 = EnumConverter.ToListOfValues();
       Array data = EnumConverter.ToValueArray();
    

提交回复
热议问题