枚举中定义的项目总数

发布于 2024-07-20 03:55:17 字数 21 浏览 3 评论 0原文

如何获取枚举中定义的项目数?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

格子衫的從容 2024-07-27 03:55:17

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;
南冥有猫 2024-07-27 03:55:17

问题是:

如何获取枚举中定义的项目数?

“物品”的数量实际上可能意味着两种完全不同的事物。 考虑以下示例。

enum MyEnum
{
    A = 1,
    B = 2,
    C = 1,
    D = 3,
    E = 2
}

MyEnum 中定义的“项目”数量是多少?

物品数量是 5 吗? (A, B, C, D, E)

还是 3 ? (1, 2, 3)

MyEnum 中定义的名称数量 ( 5) 可按下式计算。

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

MyEnum (3) 中定义的数量可以按如下方式计算。

var valuesCount = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Distinct().Count();

The question is:

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

The number of "items" could really mean two completely different things. Consider the following example.

enum MyEnum
{
    A = 1,
    B = 2,
    C = 1,
    D = 3,
    E = 2
}

What is the number of "items" defined in MyEnum?

Is the number of items 5? (A, B, C, D, E)

Or is it 3? (1, 2, 3)

The number of names defined in MyEnum (5) can be computed as follows.

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

The number of values defined in MyEnum (3) can be computed as follows.

var valuesCount = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Distinct().Count();
任谁 2024-07-27 03:55:17

Enum.GetValues(typeof(MyEnum)).Length ;

Enum.GetValues(typeof(MyEnum)).Length;

梦开始←不甜 2024-07-27 03:55:17

我今天运行了一个基准测试并得出了有趣的结果。 在这三个中:

var count1 = typeof(TestEnum).GetFields().Length;
var count2 = Enum.GetNames(typeof(TestEnum)).Length;
var count3 = Enum.GetValues(typeof(TestEnum)).Length;

GetNames(enum) 是迄今为止最快的!

|         Method |      Mean |    Error |   StdDev |
|--------------- |---------- |--------- |--------- |
| DeclaredFields |  94.12 ns | 0.878 ns | 0.778 ns |
|       GetNames |  47.15 ns | 0.554 ns | 0.491 ns |
|      GetValues | 671.30 ns | 5.667 ns | 4.732 ns |

I've run a benchmark today and came up with interesting result. Among these three:

var count1 = typeof(TestEnum).GetFields().Length;
var count2 = Enum.GetNames(typeof(TestEnum)).Length;
var count3 = Enum.GetValues(typeof(TestEnum)).Length;

GetNames(enum) is by far the fastest!

|         Method |      Mean |    Error |   StdDev |
|--------------- |---------- |--------- |--------- |
| DeclaredFields |  94.12 ns | 0.878 ns | 0.778 ns |
|       GetNames |  47.15 ns | 0.554 ns | 0.491 ns |
|      GetValues | 671.30 ns | 5.667 ns | 4.732 ns |
甜`诱少女 2024-07-27 03:55:17

我在这个问题的 C 答案中看到了一个巧妙的技巧,只需将最后一个元素添加到枚举中,并用它来告诉枚举中有多少个元素:

enum MyType {
  Type1,
  Type2,
  Type3,
  NumberOfTypes
}

在定义除 0 以外的起始值的情况下,您可以使用 NumberOfTypes - Type1 来确定元素的数量。

我不确定这种方法是否比使用 Enum 更快,而且我也不确定它是否被认为是执行此操作的正确方法,因为我们有 Enum 来为我们确定此信息。

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.

咽泪装欢 2024-07-27 03:55:17

您可以使用 Enum.GetNames 返回枚举中的 IEnumerable 值,然后。 对结果 IEnumerable 进行计数

GetNames 生成的结果与 GetValues 大致相同,但速度更快。

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.

箜明 2024-07-27 03:55:17

从前面的答案中仅添加代码示例。

 class Program
    {
        static void Main(string[] args)
        {
            int enumlen = Enum.GetNames(typeof(myenum)).Length;
            Console.Write(enumlen);
            Console.Read();
        }
        public enum myenum
        {
            value1,
            value2
        }
    }

From the previous answers just adding code sample.

 class Program
    {
        static void Main(string[] args)
        {
            int enumlen = Enum.GetNames(typeof(myenum)).Length;
            Console.Write(enumlen);
            Console.Read();
        }
        public enum myenum
        {
            value1,
            value2
        }
    }
失去的东西太少 2024-07-27 03:55:17

如果您发现自己像我一样经常编写上述解决方案,那么您可以将其实现为通用的:

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;
}

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;
}
御守 2024-07-27 03:55:17

对于 Visual Basic:

[Enum].GetNames(typeof(MyEnum)).Length 不适用于我,但是
[Enum].GetNames(GetType(Animal_Type)).length 做到了。

For Visual Basic:

[Enum].GetNames(typeof(MyEnum)).Length did not work with me, but
[Enum].GetNames(GetType(Animal_Type)).length did.

深居我梦 2024-07-27 03:55:17

我刚刚正在研究这个问题,并对当前解决方案的可读性不满意。 如果您正在非正式地或在小型项目中编写代码,则只需在枚举末尾添加另一个名为“Length”的项目即可。 这样,您只需要输入:

var namesCount = (int)MyEnum.Length;

当然,如果其他人要使用您的代码 - 或者我确信在许多其他情况下,在这种情况下不适用于我 - 这个解决方案可能是从不明智到糟糕的任何地方。

I was looking into this just now, and wasn't happy with the readability of the current solution. If you're writing code informally or on a small project, you can just add another item to the end of your enum called "Length". This way, you only need to type:

var namesCount = (int)MyEnum.Length;

Of course if others are going to use your code - or I'm sure under many other circumstances that didn't apply to me in this case - this solution may be anywhere from ill advised to terrible.

埋葬我深情 2024-07-27 03:55:17

对于通用 GetNames() 重载,有一种更简洁的方法:

int itemCount = Enum.GetNames<MyEnum>().Length;

Enum.GetNames<>() 方法

There is a more concise way with the generic GetNames() overload:

int itemCount = Enum.GetNames<MyEnum>().Length;

Enum.GetNames<>() method

回忆追雨的时光 2024-07-27 03:55:17

如果只是为了知道 ENUM 里面有多少项。 我将这样做:

enum MyEnum()
{
  FIRST =  0,
  SECOND = 1,

  TOTAL_ENUM_ITEM
}

最后一个 ENUM 项目 MyEnum.TOTAL_ENUM_ITEM 将向您显示 ENUM 内的项目数。

这并不花哨,但很有效:)

If it only to know how many items inside the ENUM. I will do this instead:

enum MyEnum()
{
  FIRST =  0,
  SECOND = 1,

  TOTAL_ENUM_ITEM
}

The last ENUM item MyEnum.TOTAL_ENUM_ITEM will show you the number of items inside the ENUM.

It's not fancy, but it works :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文