enum bitwise/flags 实例枚举/迭代/foreach
整个枚举迭代
foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
// ...
}
但是如何迭代按位枚举实例呢?
Suit mySuits = Suit.Hearts | Suit.Diamonds;
// How to now iterate mySuits, which should loop twice instead of four times?
Whole enum iteration
foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
// ...
}
But how To iterate a bitwise enum Instance?
Suit mySuits = Suit.Hearts | Suit.Diamonds;
// How to now iterate mySuits, which should loop twice instead of four times?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设
Suit
是一个没有重叠值的按位枚举,那么这就足够了:如果它需要快速,或者如果它需要忽略复合值或零值,那么您可能应该检查在
for
循环中连续计算 2 的幂,并确定哪些值与该方式匹配。Assuming
Suit
is a bitwise enum with no overlapping values, then this would be sufficient:If it needs to be fast, or if it needs to ignore composite values or a zero value, then you should probably instead check successive powers of two in a
for
loop and identify which values match that way.我的建议:
My suggestion:
不完美(拳击),但它完成了工作......
用法:
Not perfect (boxing), but it does the job...
Usage:
枚举只是一种值类型 - 它是不可迭代的。
An enum is just a value type - it is not iterable.