Total number of items defined in an enum

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

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

10条回答
  •  眼角桃花
    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() where T : struct, IConvertible 
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException("T must be an enumerated type");
    
        return Enum.GetNames(typeof(T)).Length;
    }
    

提交回复
热议问题