通过整数类型枚举进行简单迭代?
我有以下枚举:
Public Enum myEnum As Integer
first = &H1
second = &H2
third = &H4
fourth = &H8
fifth = &H10
sixth = &H20
End Enum
不幸的是,枚举元素必须具有这些值,或者至少具有可以进行二进制比较的值。
我有一个类,可以在构造期间设置为两种类型之一,一种类型具有与第一到第四相关的值,第二种类型具有与第一到第六相关的值。
我想使用 For 循环来迭代枚举的 1-4 或 1-6 个元素,但我发现此代码:
For enumType as myEnum = myEnum.first to myEnum.fourth
Next
迭代 {1,2,3,4,5,6,7,8}而不是通过 {1,2,4,8}。
这并不理想。
显然,我可以围绕这个问题进行编码,但我可以看到在维护编程中很容易错过该解决方法的情况,并且我希望有人可以推荐一个不会破坏的简单解决方案,例如,如果枚举必须在以后更改。
I have the following Enum:
Public Enum myEnum As Integer
first = &H1
second = &H2
third = &H4
fourth = &H8
fifth = &H10
sixth = &H20
End Enum
It is neccessary, unfortunately, that the enum elements have those values, or at least have values that can be binary compared.
I have a class which can be set during construction to be one of two types, a type with values relating to first through fourth, and a second type with values relating to first through sixth.
I would like to use a For loop to iterate through 1-4 or 1-6 elements of the enum, but I have found that this code:
For enumType as myEnum = myEnum.first to myEnum.fourth
Next
iterates through {1,2,3,4,5,6,7,8} and not through {1,2,4,8}.
This is not ideal.
Obviously I can code around this issue, but I can see a scenario where that workaround could be easily missed in maintenance programming, and I'm hoping someone can recommend a simple solution that won't break if, for example, the values in the enum have to change at a later date.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
抱歉,C#:
Sorry for C#:
我希望您需要使用
Enum.GetValues()
,并将结果过滤为您想要的结果。 例如,使用 LINQ )(并使用 C#,因为我不太了解 VB):(注意:这里重要的是
GetValues
- VB 和 C# 之间应该是相同的)I expect you'll need to use
Enum.GetValues()
, and filter the results to what you want. For example, using LINQ )(and using C#, as I don't know VB well enough):(note: the important thing here is the
GetValues
- which should be identical between VB and C#)Marc 基本上是正确的,除了您不需要显式排序(Enum.GetValues 已经返回排序),并且您需要对输出进行强制转换:
Marc is basically right, except that you don't need to explicitly sort (Enum.GetValues already returns sorted), and you need to cast for output:
我知道这个问题已经得到了回答,但在我看来,这似乎是想太多了。 为什么不这样做呢?
I know that this has already been answered, but it seems to me that this has been over thought. Why not do this?
查看
Enum.GetValues(Type)
Look at
Enum.GetValues(Type)