Total number of items defined in an enum

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

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

10条回答
  •  旧巷少年郎
    2020-11-30 19:22

    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 |
    

提交回复
热议问题