How to enumerate an enum

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

    Three ways:

    1. Enum.GetValues(type) // Since .NET 1.1, not in Silverlight or .NET Compact Framework
    2. type.GetEnumValues() // Only on .NET 4 and above
    3. type.GetFields().Where(x => x.IsLiteral).Select(x => x.GetValue(null)) // Works everywhere

    I am not sure why GetEnumValues was introduced on type instances. It isn't very readable at all for me.


    Having a helper class like Enum is what is most readable and memorable for me:

    public static class Enum where T : struct, IComparable, IFormattable, IConvertible
    {
        public static IEnumerable GetValues()
        {
            return (T[])Enum.GetValues(typeof(T));
        }
    
        public static IEnumerable GetNames()
        {
            return Enum.GetNames(typeof(T));
        }
    }
    

    Now you call:

    Enum.GetValues();
    
    // Or
    Enum.GetValues(typeof(Suit)); // Pretty consistent style
    

    One can also use some sort of caching if performance matters, but I don't expect this to be an issue at all.

    public static class Enum where T : struct, IComparable, IFormattable, IConvertible
    {
        // Lazily loaded
        static T[] values;
        static string[] names;
    
        public static IEnumerable GetValues()
        {
            return values ?? (values = (T[])Enum.GetValues(typeof(T)));
        }
    
        public static IEnumerable GetNames()
        {
            return names ?? (names = Enum.GetNames(typeof(T)));
        }
    }
    

提交回复
热议问题