Total number of items defined in an enum

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

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

10条回答
  •  不知归路
    2020-11-30 19:20

    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.

提交回复
热议问题