How to enumerate an enum

后端 未结 29 2570
深忆病人
深忆病人 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:43

    What if you know the type will be an enum, but you don't know what the exact type is at compile time?

    public class EnumHelper
    {
        public static IEnumerable GetValues()
        {
            return Enum.GetValues(typeof(T)).Cast();
        }
    
        public static IEnumerable getListOfEnum(Type type)
        {
            MethodInfo getValuesMethod = typeof(EnumHelper).GetMethod("GetValues").MakeGenericMethod(type);
            return (IEnumerable)getValuesMethod.Invoke(null, null);
        }
    }
    

    The method getListOfEnum uses reflection to take any enum type and returns an IEnumerable of all enum values.

    Usage:

    Type myType = someEnumValue.GetType();
    
    IEnumerable resultEnumerable = getListOfEnum(myType);
    
    foreach (var item in resultEnumerable)
    {
        Console.WriteLine(String.Format("Item: {0} Value: {1}",item.ToString(),(int)item));
    }
    

提交回复
热议问题