标记枚举中的值迭代?(Iterate over values in Flags Enum?)

编程入门 行业动态 更新时间:2024-10-25 16:30:57
标记枚举中的值迭代?(Iterate over values in Flags Enum?)

如果我有一个持有一个标志枚举的变量,我可以以某种方式迭代该特定变量中的位值吗? 或者我必须使用Enum.GetValues遍历整个枚举,并检查哪些设置?

If I have a variable holding a flags enum, can I somehow iterate over the bit values in that specific variable? Or do I have to use Enum.GetValues to iterate over the entire enum and check which ones are set?

最满意答案

static IEnumerable<Enum> GetFlags(Enum input) { foreach (Enum value in Enum.GetValues(input.GetType())) if (input.HasFlag(value)) yield return value; }

Coming back at this a few years later, with a bit more experience, my ultimate answer for single-bit values only, moving from lowest bit to highest bit, is a slight variant of Jeff Mercado's inner routine:

public static IEnumerable<Enum> GetUniqueFlags(this Enum flags) { ulong flag = 1; foreach (var value in Enum.GetValues(flags.GetType()).Cast<Enum>()) { ulong bits = Convert.ToUInt64(value); while (flag < bits) { flag <<= 1; } if (flag == bits && flags.HasFlag(value)) { yield return value; } } }

It seems to work, and despite my objections of some years ago, I use HasFlag here, since it's far more legible than using bitwise comparisons and the speed difference is insignificant for anything I'll be doing. (It's entirely possible they've improved the speed of HasFlags since then anyway, for all I know...I haven't tested.)

更多推荐

本文发布于:2023-04-29 11:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336279.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:标记   迭代   Iterate   Enum   Flags

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!