【问题标题】:How to determine the no of enum items declared in c# [duplicate]如何确定在c#中声明的枚举项的数量[重复]
【发布时间】:2014-05-31 03:16:00
【问题描述】:

我需要知道已声明的枚举数。 到目前为止,我正在使用以下方法,但我想知道是否有更好的方法?

 enum MyEnum 
 {
  foo = 1,
  bar = 2
 }

int noOfEnums = Enum.GetNames(typeof(MyEnum)).Count();

noOfEnums 将为 2;

【问题讨论】:

  • Enum.GetNames(typeof(MyEnum)).Length 稍微好一点。 :)
  • @Dmitry d'oh,正是我要说的;p
  • @Dmitry 为什么这样更好?
  • 因为与枚举IEnumerable相比,每次访问数组时都不会计算数组的长度。

标签: c# .net enums


【解决方案1】:

您可以尝试使用:

enum MyEnum 
{
  foo = 1,
  bar = 2
}

var noOfEnums = Enum.GetNames(typeof(MyEnum)).Length;

这个数组的长度属性等于枚举中定义的项目数

同时检查Count Items in a C# Enum

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 2013-05-28
    相关资源
    最近更新 更多