Total number of items defined in an enum

前端 未结 10 698
你的背包
你的背包 2020-11-30 18:36

How can I get the number of items defined in an enum?

相关标签:
10条回答
  • 2020-11-30 19:29

    You can use the static method Enum.GetNames which returns an array representing the names of all the items in the enum. The length property of this array equals the number of items defined in the enum

    var myEnumMemberCount = Enum.GetNames(typeof(MyEnum)).Length;
    
    0 讨论(0)
  • 2020-11-30 19:31

    You can use Enum.GetNames to return an IEnumerable of values in your enum and then .Count the resulting IEnumerable.

    GetNames produces much the same result as GetValues but is faster.

    0 讨论(0)
  • 2020-11-30 19:37

    A nifty trick I saw in a C answer to this question, just add a last element to the enum and use it to tell how many elements are in the enum:

    enum MyType {
      Type1,
      Type2,
      Type3,
      NumberOfTypes
    }
    

    In the case where you're defining a start value other than 0, you can use NumberOfTypes - Type1 to ascertain the number of elements.

    I'm unsure if this method would be faster than using Enum, and I'm also not sure if it would be considered the proper way to do this, since we have Enum to ascertain this information for us.

    0 讨论(0)
  • 2020-11-30 19:39

    If you find yourself writing the above solution as often as I do then you could implement it as a generic:

    public static int GetEnumEntries<T>() where T : struct, IConvertible 
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException("T must be an enumerated type");
    
        return Enum.GetNames(typeof(T)).Length;
    }
    
    0 讨论(0)
提交回复
热议问题