How to enumerate an enum

后端 未结 29 1864
深忆病人
深忆病人 2020-11-22 01:14

How can you enumerate an enum in C#?

E.g. the following code does not compile:

public enum Suit
{         


        
29条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 01:50

    You won't get Enum.GetValues() in Silverlight.

    Original Blog Post by Einar Ingebrigtsen:

    public class EnumHelper
    {
        public static T[] GetValues()
        {
            Type enumType = typeof(T);
    
            if (!enumType.IsEnum)
            {
                throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
            }
    
            List values = new List();
    
            var fields = from field in enumType.GetFields()
                         where field.IsLiteral
                         select field;
    
            foreach (FieldInfo field in fields)
            {
                object value = field.GetValue(enumType);
                values.Add((T)value);
            }
    
            return values.ToArray();
        }
    
        public static object[] GetValues(Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
            }
    
            List values = new List();
    
            var fields = from field in enumType.GetFields()
                         where field.IsLiteral
                         select field;
    
            foreach (FieldInfo field in fields)
            {
                object value = field.GetValue(enumType);
                values.Add(value);
            }
    
            return values.ToArray();
        }
    }
    
        

    提交回复
    热议问题