Enum.GetValues() Return Type

后端 未结 6 640
孤独总比滥情好
孤独总比滥情好 2020-12-01 11:45

I have read documentation that states that ‘given the type of the enum, the GetValues() method of System.Enum will return an array of the given enum\'s base type’ ie int, by

6条回答
  •  青春惊慌失措
    2020-12-01 12:23

    Similar to Joel's Answer but done a slight different way:

    public static class Enums
      where T : struct, IComparable, IFormattable, IConvertible
    {
      static Enums()
      {
        if (!typeof(T).IsEnum)
          throw new ArgumentException("Type T must be an Enum type");  
      }
    
      public static IEnumerable GetValues()
      {
        var result = ((T[])Enum.GetValues(typeof(T)).ToList()
    
        return result;
      }
    }
    

    Usage:

    IEnumerable styles = Enums.GetValues();
    

提交回复
热议问题