How to enumerate an enum

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

    Just by combining the top answers, I threw together a very simple extension:

    public static class EnumExtensions
    {
        /// 
        /// Gets all items for an enum value.
        /// 
        /// 
        /// The value.
        /// 
        public static IEnumerable GetAllItems(this T value) where T : Enum
        {
            return (T[])Enum.GetValues(typeof (T));
        }
    }
    

    It is clean, simple, and, by @Jeppe-Stig-Nielsen's comment, fast.

提交回复
热议问题